<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="dialogTile"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    v-loading="addDialogLoading"
    width="80%"
  >
    <el-form
      :model="addForm"
      class="add_form"
      ref="addFormRef"
      :rules="rules"
      label-width="110px"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="计划配置单号" prop="code">
            <el-input
              v-model="addForm.planCode"
              placeholder="自动生成"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划配置名称" prop="planName">
            <el-input
              v-model="addForm.planName"
              placeholder="请输入"
              :disabled="isBindPlan"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="自动派单" prop="autoOrder">
            <el-select
              v-model="addForm.autoOrder"
              class="w100"
              placeholder="请选择"
              :disabled="isBindPlan"
              filterable
            >
              <el-option :value="1" label="是"></el-option>
              <el-option :value="0" label="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规则名称" prop="ruleId">
            <el-select
              v-model="addForm.ruleId"
              class="w100"
              placeholder="请选择规则名称"
              @change="change_ruleId"
              :disabled="isBindPlan"
              filterable
            >
              <el-option
                v-for="item in ruleNameList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                @click.native="addForm.ruleName = item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划盘点时长" prop="duration">
            <el-input
              v-model.number="addForm.duration"
              placeholder="请输入"
              :disabled="isBindPlan"
            >
              <template #suffix>分钟</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点类型" prop="inventoryType">
            <el-select
              v-model="addForm.inventoryType"
              class="w100"
              placeholder="请选择"
              @change="chooseType"
              disabled
              filterable
            >
              <el-option
                v-for="item in inventoryTypeStatus"
                :key="item.code"
                :value="item.code"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="addForm.inventoryType == 1" :span="8">
          <el-form-item label="盘点仓库" prop="warehouseId">
            <el-select
              placeholder="请选择"
              class="w100"
              :disabled="isBindPlan"
              v-model="addForm.warehouseId"
              @change="changeWarehouse"
              filterable
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                @click.native="
                  () => {
                    addForm.bizTypeName = item.name;
                  }
                "
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="审核人" prop="verifyUserId">
            <el-select
              v-model="addForm.verifyUserId"
              size="small"
              style="width: 100%"
              :disabled="isBindPlan"
              filterable
            >
              <el-option
                v-for="item in uerList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->

        <el-col :span="8">
          <el-form-item
            :label="type == 2 ? '产品分类' : '资产分类'"
            prop="categoryLevelId"
          >
            <ele-tree-select
              multiple
              clearable
              :disabled="isBindPlan"
              :data="codeList"
              @change="codeListValue"
              v-model="addForm.categoryLevelId"
              valueKey="id"
              labelKey="name"
              :show-checkbox="true"
              :check-strictly="true"
              filterable
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="紧急程度" prop="urgent">
            <DictSelection
              :isProhibit="isBindPlan"
              dictName="紧急程度"
              clearable
              filterable
              v-model="addForm.urgent"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="addForm.autoOrder">
          <el-form-item label="执行部门" prop="executeGroupId">
            <deptSelect
              :isBindPlan="isBindPlan"
              v-model="addForm.executeGroupId"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="addForm.autoOrder">
          <el-form-item label="执行人员" prop="executorId">
            <el-select
              v-model="addForm.executorId"
              @change="changeExecutor"
              :disabled="isBindPlan"
              size="small"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="item in executorList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="addForm.inventoryType == 1" :span="8">
          <el-form-item label="锁库盘点" prop="isTreasuryLock">
            <el-switch
              v-model="addForm.lockWarehouse"
              active-text="开"
              inactive-text="关"
              :active-value="1"
              :inactive-value="0"
              :disabled="isBindPlan"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="enable">
            <el-switch
              v-model="addForm.enable"
              :disabled="isBindPlan"
              active-text="开"
              inactive-text="关"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              placeholder="请输入"
              type="textarea"
              :rows="2"
              resize="none"
              v-model="addForm.remark"
              :disabled="isBindPlan"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="table_search">
        <el-select
          style="margin-right: 10px"
          :disabled="isBindPlan"
          @change="dimensionChange"
          v-model="dimension"
          placeholder="请选择维度"
        >
          <el-option label="物品维度" :value="1"> </el-option>
          <el-option label="批次维度" :value="2"> </el-option>
        </el-select>
        <el-input
          v-if="!isBindPlan"
          style="width: 400px"
          placeholder="请输入名称/编码/批次号/型号/规格"
          v-model="keyWord"
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            type="primary"
            @click="getProductList"
            >搜索</el-button
          >
        </el-input>
      </div>
      <el-table
        ref="table"
        :data="productList"
        row-key="id"
        @selection-change="selecctedRow"
        tooltip-effect="dark"
        border
      >
        <el-table-column
          v-if="!isBindPlan"
          align="center"
          width="50"
          :reserve-selection="true"
          :selectable="checkSelectable"
          type="selection"
        ></el-table-column>
        <el-table-column label="序号" type="index" width="50">
        </el-table-column>
        <el-table-column
          label="物品编码"
          prop="categoryCode"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="物品名称"
          prop="categoryName"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="批次号"
          prop="batchNo"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="牌号"
          prop="brandNum"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="型号"
          prop="categoryModel"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="规格"
          prop="specification"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="计量数量"
          prop="measureQuantity"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="计量单位"
          prop="measureUnit"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="重量"
          prop="weight"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="重量单位"
          prop="weightUnit"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="!isBindPlan"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :page-size.sync="size"
        :current-page.sync="page"
        @current-change="getProductList"
        @size-change="getProductList"
      >
      </el-pagination>
      <!-- 库外 -->
      <!-- <Assets
        ref="assetsRef"
        :assetsName="addForm.assetsName"
        :assetsType="assetsType"
        :planRuleInventoryDetailList="planRuleInventoryDetailList"
        :isBindPlan = "isBindPlan"
        v-if="
          addForm.bizType === 2 &&
          addForm.assetsName != '物料' &&
          addForm.assetsName != '产品' &&
          addForm.assetsName != '备品备件'
        "
      /> -->
      <!-- 库内 库存台账 -->
      <AssetsInWarehouse
        ref="assetsRef"
        :assetsName="addForm.assetsName"
        :warehouseId="addForm.bizTypeId"
        :assetsType="assetsType"
        :bizType="addForm.inventoryType"
        :planRuleInventoryDetailList="planRuleInventoryDetailList"
        :isBindPlan="isBindPlan"
      />
    </el-form>
    <div v-if="!isBindPlan" slot="footer">
      <el-button type="primary" size="small" @click="submit">提交</el-button>
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
    <div v-else slot="footer">
      <el-button type="primary" size="small" @click="dialogVisible = false"
        >确定</el-button
      >
      <el-button size="small" @click="dialogVisible = false">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getFactoryarea } from '@/api/factoryModel';
  import { listWorkshopByParentId, listFactoryLine } from '@/api/factoryModel';
  import { listByProductionLineId } from '@/api/workforceManagement/team';
  import selectTree from '@/components/selectTree/index_other.vue';
  import { getTreeByGroup } from '@/api/classifyManage';
  import { inventoryTypeStatus } from '@/utils/dict/rulesManagement';
  import { mapGetters } from 'vuex';
  // import { wh_checkStatus} from '@/utils/dict/warehouse'
  import { getCode } from '@/api/ruleManagement/matter';
  import AssetsInWarehouse from './AssetsInWarehouse';
  import { fieldModel } from '@/api/codeManagement';
  import {
    getRule,
    getProductList,
    getBatchList,
    getWarehouseList,
    saveStocktakingPlan,
    updateStocktakingPlan,
    getInventoryDetailById
  } from '@/api/ruleManagement/plan';
  import { getUserPage } from '@/api/system/organization';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  export default {
    props: {
      dialogTile: {
        type: String,
        default: '新增盘点计划配置'
      },
      isBindPlan: {
        type: Boolean,
        default: function () {
          return false;
        }
      },
      id: {
        type: String,
        default: ''
      }
    },
    components: {
      deptSelect,
      AssetsInWarehouse,
      selectTree
    },
    data() {
      return {
        type: 2, // 盘点类型 2仓储 4资产
        dimension: 1, // 盘点维度1物品 2批次
        factoryOptions: [],
        workshopOptions: [],
        productionLineOptions: [],
        stationOptions: [],
        codeList: [],
        inventoryTypeStatus,
        addDialogLoading: false,
        dialogVisible: false,
        wh_checkStatus: [], // 盘点类型
        warehouseList: [], // 盘点仓库
        uerList: [], // 审核人
        executorList: [], // 执行人
        assetsType: null,
        planRuleInventoryDetailList: [],
        tableList: [],
        newColumns: [],
        selection: [],
        keyWord: '',
        total: 0,
        page: 1,
        size: 10,
        productList: [],
        addForm: {
          code: '', // 计划配置单号
          planName: '', // 计划配置名称
          categoryId: 0, // 类别ID
          autoOrder: 1, // 是否自动派单
          ruleId: '', // 规则名称
          categoryLevelId: [], // 物品Ids
          inventoryType: 1, // 盘点类型
          bizTypeId: '', // 盘点仓库Id
          bizTypeName: '', // 盘点仓库name
          verifyUserId: '', // 审核人Id
          verifyUserName: '', // 审核人name
          duration: null, // 盘点时长
          assetDict: '', // 资产分类id
          assetsName: '', // 资产分类name
          urgent: '1', // 紧急程度
          executeGroupId: '', // 执行部门code
          executeGroupName: '', // 执行部门name
          executorId: '', // 执行人id
          executorName: '', // 执行人name
          isTreasuryLock: false, // 是否锁库盘点
          enable: 1, // 状态
          remark: '', // 备注
          productionLineId: '',
          productionLineName: '',
          workshopId: '',
          workshopName: '',
          plantId: '',
          plantName: '',
          stationId: '',
          stationName: ''
        },
        rules: {
          planName: [
            { required: true, message: '请输入计划配置名称', trigger: 'blur' }
          ],
          autoOrder: [
            { required: true, message: '请选择是否自动派单', trigger: 'change' }
          ],
          ruleId: [
            { required: true, message: '请选择规则名称', trigger: 'change' }
          ],
          duration: [
            { required: true, message: '请输入计划完成时长', trigger: 'blur' }
          ],
          inventoryType: [
            { required: true, message: '请选择盘点类型', trigger: 'change' }
          ],
          // plantId: [
          //   {
          //     required: true,
          //     message: '请选择厂房',
          //     trigger: 'change'
          //   }
          // ],
          warehouseId: [
            { required: true, message: '请选择盘点仓库', trigger: 'change' }
          ],
          verifyUserId: [
            { required: false, message: '请选择审核人', trigger: 'change' }
          ],
          executeGroupId: [
            { required: true, message: '请选择选择执行部门', trigger: 'change' }
          ],
          executorId: [
            { required: true, message: '请选择选择执行人员', trigger: 'change' }
          ],
          assetDict: [
            { required: true, message: '请选择资产分类', trigger: 'change' }
          ]
        },
        ruleNameList: []
      };
    },
    watch: {
      dialogVisible(val) {
        if (val) {
          // // 获取审核人列表数据
          // this.getUserList();
          // 获取盘点仓库
          this._getWarehouse();
          // 获取计划单号
          this.getOrderCode();
          // 获取规则名称
          this._getRuleNameList();
          // 获取物品类型
          this.getGoodsList();
          // 获取工厂列表
          this.getFactoryareaList();
          if (
            this.dialogTile === '修改盘点计划配置' ||
            this.dialogTile === '盘点计划配置详情'
          ) {
            getInventoryDetailById(this.id).then(async (res) => {
              console.log(res);
              res.warehouseId = res.warehouseId > 0 ? res.warehouseId : '';
              res.urgent = String(res.urgent);
              res.categoryLevelId = res.categoryLevelId
                ? res.categoryLevelId.split(',')
                : [];
              this.addForm = res;
              this.dimension = res.planConfigDetailVOList[0].batch_no ? 2 : 1;
              if (this.addForm.executeGroupId) {
                this.getUserList({ groupId: this.addForm.executeGroupId });
              }
              if (this.dialogTile === '修改盘点计划配置') {
                // 回显物品列表
                let categoryIds = this.addForm.planConfigDetailVOList.map(
                  (item) => item.categoryId
                );
                await this.getProductList();
                let list = this.productList.filter((item) =>
                  categoryIds.includes(item.categoryId)
                );
                list.forEach((item) => {
                  this.$refs.table.toggleRowSelection(item);
                });
              } else {
                this.productList = res.planConfigDetailVOList;
              }
            });
          } else {
            this.productList = [];
            this.selection = [];
            this.addForm = {
              code: '', // 计划配置单号
              planName: '', // 计划配置名称
              categoryId: 0, // 类别ID
              autoOrder: 1, // 是否自动派单
              ruleId: '', // 规则名称
              categoryLevelId: [], // 物品Ids
              inventoryType: 1, // 盘点类型
              bizTypeId: '', // 盘点仓库Id
              bizTypeName: '', // 盘点仓库name
              verifyUserId: '', // 审核人Id
              verifyUserName: '', // 审核人name
              duration: null, // 盘点时长
              assetDict: '', // 资产分类id
              assetsName: '', // 资产分类name
              urgent: '1', // 紧急程度
              executeGroupId: '', // 执行部门code
              executeGroupName: '', // 执行部门name
              executorId: '', // 执行人id
              executorName: '', // 执行人name
              isTreasuryLock: false, // 是否锁库盘点
              enable: 1, // 状态
              remark: '', // 备注
              productionLineId: '',
              productionLineName: '',
              workshopId: '',
              workshopName: '',
              plantId: '',
              plantName: '',
              stationId: '',
              stationName: ''
            };
          }
        }
      },
      planRulesDetails(val) {
        if (!this.dialogVisible) return;
        this.addForm = val;
        this.addForm.assetsName = val.assetDictDESC;
        this.assetsType = val.assetDict;
        // this.warehousingType.map(item => {
        //   if (val.assetsName == item.label) {
        //     this.assetsType = item.code
        //   }
        // })
        // this.assetsType = this.warehousingType.filter(
        //   item => item.code === val.assetDict.code
        // )[0].type
        // this.addForm.assetDict = this.warehousingType.filter(
        //   item => item.code === val.assetDict.code
        // )[0].key
        // 根据部门回显人员
        const params = { deptCode: val.executeGroupId, status: 1 };
        this.getUserList(params);
        this.planRuleInventoryDetailList = val.planRuleInventoryDetailList;
        console.log(
          'planRuleInventoryDetailList',
          this.planRuleInventoryDetailList
        );
        // 将 planRuleInventoryDetailList 保存到store,在 assets.vue 中获取用来高亮树节点和请求右边的列表
        // 取出 planRuleInventoryDetailList 里面的分类 bizTypeId、bizTypeName，用来高亮树节点和请求右边的列表
        // console.log('资产分类：', val.assetDict)
        // console.log(this.addForm.assetsName)
      }
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },
    methods: {
      selecctedRow(val) {
        this.selection = val;
      },
      dimensionChange() {
        this.selection = [];
        this.$refs.table.clearSelection();
        if (this.addForm.warehouseId) {
          this.getProductList();
        }
      },
      checkSelectable(row) {
        return true;
      },
      async getProductList() {
        let data = null;
        if (this.dimension == 1) {
          data = await getProductList({
            keyWord: this.keyWord,
            warehouseId: this.type == 2 ? this.addForm?.warehouseId : '',
            categoryLevelIds: this.addForm?.categoryLevelId.join(','),
            pageNum: this.page,
            size: this.size
          });
        } else {
          data = await getBatchList({
            keyWord: this.keyWord,
            warehouseId: this.type == 2 ? this.addForm?.warehouseId : '',
            categoryLevelIds: this.addForm?.categoryLevelId.join(','),
            pageNum: this.page,
            size: this.size
          });
        }
        this.total = data.count;
        this.productList = data.list;
      },
      // 改变规则名称
      change_ruleId(val) {
        this.addForm.ruleName = this.ruleNameList.filter(
          (item) => item.id === val
        )[0].name;
      },
      // 获取工厂数据
      getFactoryareaList() {
        getFactoryarea({
          type: 1,
          size: 9999,
          type: 2
        }).then((res) => {
          this.factoryOptions = res.list;
        });
      },
      change_factoryId(id) {
        this.addForm.workshopId = '';
        this.addForm.productionLineId = '';
        this.addForm.stationId = '';
        this.workshopOptions = [];
        this.productionLineOptions = [];
        this.stationOptions = [];
        this.addForm.plantId = id;
        this.addForm.plantName = this.factoryOptions.filter(
          (item) => item.id === id
        )[0].pathName;
        this.getListWorkshopByParentId(id);
      },
      // 获取车间
      getListWorkshopByParentId(id) {
        listWorkshopByParentId(id).then((res) => {
          this.workshopOptions = res;
        });
      },
      change_workshop(id) {
        this.addForm.productionLineId = '';
        this.addForm.stationId = '';
        this.productionLineOptions = [];
        this.stationOptions = [];
        this.addForm.workshopName = this.workshopOptions.filter(
          (item) => item.id === id
        )[0].name;
        this.getlistFactoryLineByParentId(id);
      },
      // 获取产线
      getlistFactoryLineByParentId(id) {
        listFactoryLine([id]).then((res) => {
          this.productionLineOptions = res;
        });
      },
      change_productionLineId(id) {
        this.addForm.stationId = '';
        this.stationOptions = [];
        this.addForm.productionLineName = this.productionLineOptions.filter(
          (item) => item.id === id
        )[0].name;
        this.getlistByProductionLineId(id);
      },
      // 获取工位
      getlistByProductionLineId(id) {
        listByProductionLineId(id).then((res) => {
          this.stationOptions = res;
        });
      },
      change_stationId(id) {
        this.$forceUpdate();
        this.addForm.stationName = this.stationOptions.filter(
          (item) => item.id === id
        )[0].name;
      },
      // 物品类型选择
      async codeListValue(val) {
        if (this.addForm.warehouseId) {
          console.log('val---------', val);
          this.addForm.categoryLevelId = val;
          this.getProductList();
        }
      },
      // 获取物品类型列表
      async getGoodsList() {
        const { data } = await getTreeByGroup({ type: this.type });
        console.log('data------', data);
        this.codeList = data;
      },
      // 获取规则名列表
      async _getRuleNameList() {
        const res = await getRule({ status: 1, type: 4, pageNum: 1, size: -1 });
        if (res.list) {
          this.ruleNameList = res.list || [];
        }
      },
      // 获取计划配置单号
      async getOrderCode(tips) {
        const code = await getCode('inventoryconfig_code');
        this.$set(this.addForm, 'planCode', code);
      },
      // 执行人选择
      changeExecutor(val) {
        if (val) {
          this.addForm.executorId = val;
          this.addForm.executorName = this.executorList.filter(
            (item) => item.id === val
          )[0].name;
        }
      },
      // 仓库选择
      changeWarehouse(val) {
        if (val) {
          this.addForm.warehouseId = val;
          this.addForm.warehouseName = this.warehouseList.filter(
            (item) => item.id === val
          )[0].name;
        }
        this.getProductList();
      },
      // 关闭弹窗
      handleClose() {
        this.dialogVisible = false;
        this.$refs.addFormRef.resetFields();
        if (this.$refs.searchTree) {
          this.$refs.searchTree.clearHandle();
        }
        if (this.addForm.inventoryType == 2) {
          this.$refs.assetsRef._clearTreeTableData();
        }
        this.addForm.assetsName = '';
        this.assetsType = null;
        this.addForm = {
          code: '', // 计划配置单号
          planName: '', // 计划配置名称
          categoryId: 0,
          autoOrder: 1, // 是否自动派单
          ruleId: '', // 规则名称
          inventoryType: '', // 盘点类型
          bizTypeId: '', // 盘点仓库Id
          bizTypeName: '', // 盘点仓库name
          verifyUserId: '', // 审核人Id
          verifyUserName: '', // 审核人name
          duration: null, // 盘点时长
          assetDict: '', // 资产分类id
          assetsName: '', // 资产分类name
          urgent: '1', // 紧急程度
          executeGroupId: '', // 执行部门code
          executeGroupName: '', // 执行部门name
          executorId: '', // 执行人id
          executorName: '', // 执行人name
          isTreasuryLock: false, // 是否锁库盘点
          enable: 1, // 状态
          remark: '' // 备注
        };
      },

      // 封装 - 获取盘点仓库
      async _getWarehouse() {
        const res = await getWarehouseList({});
        console.log(res);
        this.warehouseList = res.map((item) => {
          return { ...item, name: item.factoryName + '-' + item.name };
        });
      },

      //选择部门(搜索)
      searchDeptNodeClick(info, row) {
        if (info) {
          const params = { groupId: info };
          this.getUserList(params);
          this.addForm.executeGroupName = row.name;
        } else {
          this.addForm.executeGroupId = null;
        }
      },

      // 获取审核人列表、巡点检人员
      async getUserList(params) {
        try {
          let data = { pageNum: 1, size: -1 };
          // 如果传了参数就是获取巡点检人员数据
          if (params) {
            data = Object.assign(data, params);
          }
          const res = await getUserPage(data);
          if (params) {
            this.executorList = res.list;
          } else {
            this.uerList = res.list;
          }
        } catch (error) {}
      },

      // 资产分类
      handleAssetsChange(item) {
        this.addForm.assetsName = item.dictValue;
        this.assetsType = item.dictCode;
        this.$nextTick(
          () =>
            this.$refs.assetsRef && this.$refs.assetsRef.handleAssetsChange()
        );
      },

      // 参数处理
      getParams() {
        const { classificationList, tableSelectionList } =
          this.$refs.assetsRef.getSelectList();
        console.log('getParams-tableSelectionList', tableSelectionList);
        return {
          ...this.addForm,
          classificationList: classificationList.map((i) => ({
            classificationID: i.id,
            classificationName: i.name
          })),
          planRuleInventoryDetailList:
            this.formData && this.formData.inventoryType === 2
              ? tableSelectionList.map((item) => ({
                  assetBrand: item.brand,
                  assetCode: item.code,
                  assetId: item.id,
                  assetLocationId: `${this.initLocation(
                    item.positionWorkshop
                  )}${this.initLocation(item.positionLine)}${this.initLocation(
                    item.positionFarm
                  )}${this.initLocation(item.positionFactory)}`,
                  assetLocationName: `${this.initLocation(
                    item.positionWorkshopCode
                  )}${this.initLocation(
                    item.positionLineCode
                  )}${this.initLocation(
                    item.positionFarmCode
                  )}${this.initLocation(item.positionFactoryCode)}`,
                  assetName: item.name,
                  assetSku: item.specifications,
                  assetTypeDict: this.addForm ? this.addForm.assetDict : '',
                  bizTypeId: item.bizTypeId,
                  bizTypeName: item.bizTypeName,
                  unit: this.addForm ? this.addForm.unit : ''
                }))
              : tableSelectionList,
          planRuleType: 'INVENTORY'
        };
      },
      initLocation(inp) {
        return inp ? inp + ',' : '';
      },

      // x选择盘点类型
      chooseType(val) {
        if (val == 2) {
          // 库外盘点
          this.addForm.warehouseId = '';
          this.addForm.warehouseName = '';
          this.addForm.lockWarehouse = 0;
          this.type = 4;
        } else {
          // 库内盘点
          this.addForm.plantId = '';
          this.addForm.workshopId = '';
          this.addForm.productionLineId = '';
          this.addForm.stationId = '';
          this.workshopOptions = [];
          this.productionLineOptions = [];
          this.stationOptions = [];
          this.type = 2;
        }
        this.addForm.categoryLevelId = [];
        this.getGoodsList();
      },
      // 提交
      // submit() {
      //   console.log(this.addForm);
      //   this.$refs.addFormRef.validate(async (valid) => {
      //     if (valid) {
      //       // const params = this.getParams();
      //       // console.log(
      //       //   'planRuleInventoryDetailList',
      //       //   params.planRuleInventoryDetailList
      //       // );
      //       // if (this.addOrUpdate != 'edit') {
      //       //   if (
      //       //     !(
      //       //       params.classificationList.length ||
      //       //       params.planRuleInventoryDetailList.length
      //       //     )
      //       //   ) {
      //       //     return this.$message.error('请选择资产分类台账！');
      //       //   }
      //       // }
      //       if (this.addForm.inventoryType == 2) {
      //         this.addForm.locationId = [
      //           this.addForm.plantId,
      //           this.addForm.workshopId,
      //           this.addForm.productionLineId,
      //           this.addForm.stationId
      //         ].join(',');
      //         this.addForm.locationName = [
      //           this.addForm.plantName,
      //           this.addForm.workshopName,
      //           this.addForm.productionLineName,
      //           this.addForm.stationName
      //         ].join(',');
      //       }
      //       if (!this.addForm.warehouseId) {
      //         this.addForm.warehouseId = 0;
      //       }
      //       if (this.addForm.inventoryType == 2 && !this.addForm.plantId) {
      //         this.$message.error('请至少选择所属厂房！');
      //         return false;
      //       }
      //       let res = '';
      //       let message = '';
      //       if (this.dialogTile === '修改盘点计划配置') {
      //         res = await updateStocktakingPlan(this.addForm);
      //         message = '修改成功！';
      //       } else {
      //         res = await saveStocktakingPlan(this.addForm);
      //         message = '新增成功！';
      //       }
      //       if (res.code == 0) {
      //         this.handleClose();
      //         this.$message.success(message);
      //         this.$emit('refreshList');
      //       }
      //     }
      //   });
      // },
      submit() {
        console.log(this.addForm);
        this.$refs.addFormRef.validate(async (valid) => {
          let res = null;
          if (valid) {
            if (this.dialogTile === '修改盘点计划配置') {
            } else {
              if (this.selection?.length > 0) {
                res = await saveStocktakingPlan({
                  ...this.addForm,
                  categoryLevelId: this.addForm.categoryLevelId.join(','),
                  details: this.selection.map((item) => {
                    return {
                      batchNo: item.batchNo,
                      categoryId: item.categoryId,
                      categoryName: item.categoryName
                    };
                  })
                });
              } else {
                return this.$message.error('请选择需要盘点物品');
              }
              console.log(this.addForm);
            }
            if (res.code == 0) {
              this.handleClose();
              this.$message.success(res.message);
              this.$emit('refreshList');
            }
          }
        });
      },
      handleChangeassetDict(data) {
        console.log(data);
      }
    }
  };
</script>

<style lang="scss" scoped>
  ::v-deep .el-row {
    display: flex;
    flex-wrap: wrap;
  }
  .add_form {
    ::v-deep .el-form-item {
      margin-bottom: 20px !important;
    }
  }
  .table_search {
    margin-bottom: 5px;
  }
</style>
