<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="inventoryType">
            <el-select
              v-model="addForm.inventoryType"
              class="w100"
              placeholder="请选择"
              @change="chooseType"
              :disabled="isBindPlan"
              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 == 2" :span="8">
          <el-form-item label="所属厂房:" prop="plantId">
            <el-select
              v-model="addForm.plantId"
              :disabled="isBindPlan"
              placeholder="请选择"
              @change="change_factoryId"
              style="width: 100%"
            >
              <el-option
                v-for="item in factoryOptions"
                :key="item.id"
                :label="item.pathName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-if="addForm.inventoryType == 2" :span="8">
          <el-form-item label="所属车间:" prop="workshopId">
            <el-select
              v-model="addForm.workshopId"
              :disabled="isBindPlan"
              placeholder="请选择"
              style="width: 100%"
              @change="change_workshop"
            >
              <el-option
                v-for="item in workshopOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col v-if="addForm.inventoryType == 2" :span="8">
          <el-form-item label="所属产线:" prop="productionLineId">
            <el-select
              v-model="addForm.productionLineId"
              :disabled="isBindPlan"
              placeholder="请选择"
              style="width: 100%"
              @change="change_productionLineId"
            >
              <el-option
                v-for="item in productionLineOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="addForm.inventoryType == 2" :span="8">
          <el-form-item label="所属工位:" prop="stationId">
            <el-select
              v-model="addForm.stationId"
              :disabled="isBindPlan"
              placeholder="请选择"
              style="width: 100%"
              @change="change_stationId"
            >
              <el-option
                v-for="item in stationOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </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"
              v-model="addForm.warehouseId"
              @change="changeWarehouse"
              :disabled="addForm.inventoryType == 2 || isBindPlan"
              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="计划盘点时长" 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="type == 2 ? '产品分类' : '资产分类'"
            prop="categoryLevelId"
          >
            <!-- <DictSelection
              dictName="类型用途"
              clearable
              filterable
              v-model="addForm.categoryLevelId"
            >
            </DictSelection> -->
            <selectTree
              :isBindPlan="isBindPlan"
              ref="tree"
              class="form-ipt"
              size="medium"
              style="width: 100%"
              :value="addForm.categoryLevelId"
              clearable
              :options="codeList"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children'
              }"
              @getValue="codeListValue"
              :isAll="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="紧急程度" prop="urgent">
            <DictSelection
              :disabled="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>
      <ele-pro-table
        ref="table"
        class="table"
        :columns="newColumns"
        :datasource="datasource"
        :selection.sync="selection"
        :initLoad="false"
        height="500px"
        tool-class="ele-toolbar-form"
        cache-key="systemOrgUserTable"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar="{ row }">
          <el-input
            style="width: 400px"
            placeholder="请输入名称/编码/批次号/型号/规格"
            v-model="keyWord"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              type="primary"
              @click="reload"
              >搜索</el-button
            >
          </el-input>
        </template>
        <!-- 最小包装单元 -->
        <template v-slot:minPackingCount="{ row }">
          <span v-if="row.minPackingCount">
            {{ row.minPackingCount }}
            {{ row.measuringUnit }}/{{ row.minUnit }}
          </span>
        </template>
        <!-- 库存保质期 -->
        <template v-slot:expirationDate="{ row }">
          <span v-if="row.expirationDate">
            {{ row.expirationDate ? row.expirationDate : '-' }}
            {{
              row.expirationDateUnit == 'year'
                ? '年'
                : row.expirationDateUnit == 'month'
                ? '月'
                : '日'
            }}
          </span>
        </template>
        <!-- 质检状态 -->
        <template v-slot:qualityStatus="{ row }">
          <span v-if="row.qualityResult == 0 || row.qualityResult == 1"
            >已检</span
          >
          <span v-else-if="row.qualityStatus == 1">已检</span>
          <span v-else-if="row.qualityStatus == 0">未检</span>
          <span v-else>-</span>
        </template>
        <!-- 质检结果 -->
        <template v-slot:qualityResult="{ row }">
          <span v-if="row.qualityResult == 0 || row.qualityResult == ''"
            >合格</span
          >
          <span v-else-if="row.qualityResult == 1">不合格</span>
          <span v-else-if="row.qualityResult == 3">让步接收</span>
          <span v-else>-</span>
        </template>
      </ele-pro-table>
      <!-- 库外 -->
      <!-- <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';
  import { getTreeByGroup } from '@/api/classifyManage';
  import { getProductList } from '@/api/ruleManagement/plan';
  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,
    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资产
        factoryOptions: [],
        workshopOptions: [],
        productionLineOptions: [],
        stationOptions: [],
        codeList: [],
        inventoryTypeStatus,
        addDialogLoading: false,
        dialogVisible: false,
        wh_checkStatus: [], // 盘点类型
        warehouseList: [], // 盘点仓库
        uerList: [], // 审核人
        executorList: [], // 执行人
        assetsType: null,
        planRuleInventoryDetailList: [],
        tableList: [],
        newColumns: [],
        selection: [],
        keyWord: '',
        columns: [
          {
            columnKey: 'selection',
            type: 'selection',
            width: 45,
            align: 'center',
            fixed: 'left'
          },
          {
            columnKey: 'index',
            type: 'index',
            width: 50,
            align: 'center',
            label: '序号',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'categoryCode',
            label: '物品编码',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryName',
            label: '物品名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryModel',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'level',
            label: '级别',
            showOverflowTooltip: true
          },
          {
            prop: 'measureQuantity',
            label: '计量数量',
            sortable: 'custom',
            showOverflowTooltip: true,
            width: 130,
            align: 'center'
          },
          {
            prop: 'measureUnit',
            label: '计量单位',
            align: 'center'
          },
          {
            prop: 'weight',
            label: '重量',
            showOverflowTooltip: true
          },
          {
            prop: 'weightUnit',
            label: '重量单位',
            showOverflowTooltip: true
          }
        ],
        addForm: {
          code: '', // 计划配置单号
          planName: '', // 计划配置名称
          categoryId: 0, // 类别ID
          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: '', // 备注
          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((res) => {
              console.log(res);
              res.warehouseId = res.warehouseId > 0 ? res.warehouseId : '';
              res.urgent = String(res.urgent);
              this.addForm = res;
              let locationIds = res.locationId && res.locationId.split(',');
              let locationNames =
                res.locationName && res.locationName.split(',');
              this.addForm.plantId = locationIds[0];
              this.addForm.workshopId = locationIds[1];
              this.addForm.productionLineId = locationIds[2];
              this.addForm.stationId = locationIds[3];
              this.addForm.plantName = locationNames[0];
              this.addForm.workshopName = locationNames[1];
              this.addForm.productionLineName = locationNames[2];
              this.addForm.stationName = locationNames[3];
              if (this.addForm.inventoryType === 2) {
                if (this.addForm.plantId) {
                  this.getListWorkshopByParentId(this.addForm.plantId);
                }
                if (this.addForm.workshopId) {
                  this.getlistFactoryLineByParentId(this.addForm.workshopId);
                }
                if (this.addForm.productionLineId) {
                  this.getlistByProductionLineId(this.addForm.productionLineId);
                }
              } else {
                this.addForm.plantId = '';
                this.addForm.workshopId = '';
                this.addForm.productionLineId = '';
                this.addForm.stationId = '';
                this.workshopOptions = [];
                this.productionLineOptions = [];
                this.stationOptions = [];
              }
              if (this.addForm.executeGroupId) {
                this.getUserList({ groupId: this.addForm.executeGroupId });
              }
            });
          } else {
            this.addForm.plantId = '';
            this.addForm.workshopId = '';
            this.addForm.productionLineId = '';
            this.addForm.stationId = '';
            this.workshopOptions = [];
            this.productionLineOptions = [];
            this.stationOptions = [];
            this.executorList = [];
          }
        }
      },
      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;
      }
    },
    created() {
      this.getFieldModel();
    },
    methods: {
      getFieldModel() {
        fieldModel({ relevance: 't_main_category' }).then((res) => {
          let newRes = res.map((m) => {
            return {
              prop: 'extField.' + m.prop,
              label: m.label,
              align: 'center',
              showOverflowTooltip: true
            };
          });

          this.newColumns = [...this.columns, ...newRes];

          this.$forceUpdate();
        });
      },
      reload() {
        this.$refs.table.reload();
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        const data = getProductList({
          ...where,
          ...order,
          keyWord: this.keyWord,
          warehouseId: this.type == 2 ? this.addForm?.warehouseId : '',
          categoryLevelId: this.addForm?.categoryLevelId,
          pageNum: page,
          size: limit
        });
        return data;
      },
      // 改变规则名称
      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) {
        console.log('val---------', val);
        this.addForm.categoryLevelId = val?.id;
        this.addForm.categoryLevelName = val?.name;
        this.$refs.table.reload();
      },
      // 获取物品类型列表
      async getGoodsList() {
        const { data } = await getTreeByGroup({ type: this.type });
        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;
        }
      },
      // 关闭弹窗
      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');
            }
          }
        });
      },
      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;
    }
  }
</style>
