<template>
  <!-- :title="`${type}临时盘点计划`" -->
  <el-dialog
    :visible.sync="visible"
    title="临时盘点计划"
    :before-close="cancel"
    width="80vw"
    class="temporary-dialog"
  >
    <el-form :model="formData" ref="formRef" :rules="rules" label-width="110px">
      <el-row :gutter="20">
        <!--        <el-col :span="8">
          <el-form-item label="计划配置单号" prop="planCode">
            <el-input
              v-model="formData.planCode"
              placeholder="自动生成"
              disabled
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="计划配置名称" prop="planName">
            <el-input
              v-model="formData.planName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="自动派单" prop="isSyncBill">
            <el-select
              filterable
              v-model="formData.isSyncBill"
              class="w100"
              placeholder="请选择"
            >
              <el-option
                v-for="item in isOrNot"
                :key="item.code"
                :value="item.code"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联事项" prop="ruleId">
            <el-select
              filterable
              v-model="formData.ruleId"
              class="w100"
              placeholder="请选择事项规则"
            >
              <el-option
                v-for="item in ruleNameList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                @click.native="() => (formData.ruleName = item.name)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点类型" prop="bizType">
            <el-select
              filterable
              v-model="formData.bizType"
              class="w100"
              placeholder="请选择"
              @change="
                () => {
                  if (formData.bizType === 2) {
                    formData.bizTypeName = '';
                    formData.bizTypeId = '';
                  }
                }
              "
            >
              <el-option
                v-for="item in wh_checkStatus"
                :key="item.code"
                :value="item.code"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="盘点仓库"
            :rules="[
              {
                required: formData.bizType !== 2,
                message: '请选择盘点仓库',
                trigger: 'blur'
              }
            ]"
            prop="bizTypeId"
          >
            <el-select
              filterable
              placeholder="请选择"
              class="w100"
              v-model="formData.bizTypeId"
              :disabled="formData.bizType === 2"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                @click.native="
                  () => {
                    formData.bizTypeName = item.name;
                  }
                "
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核部门" prop="deptName">
            <!-- <selectTree
              ref="deptRef"
              class="w100"
              :clearable="false"
              :options="deptList"
              size="small"
              :props="{
                value: 'code',
                label: 'name',
                children: 'children'
              }"
              @getValue="auditorDeptClick"
            /> -->
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审核人" prop="verifyUserId">
            <el-select
              filterable
              class="form-ipt"
              style="width: 100%"
              size="small"
              v-model="formData.verifyUserId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in auditorList"
                :key="item.userId"
                :label="item.trueName"
                :value="item.userId"
                @click.native="
                  () => {
                    formData.verifyUserName = item.trueName;
                  }
                "
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划盘点时长" prop="duration">
            <el-input v-model.number="formData.duration" placeholder="请输入">
              <template #suffix>分钟</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="资产分类" prop="assetDict">
            <!-- <el-select filterable 
              class="form-ipt"
              style="width: 100%"
              size="small"
              v-model="formData.assetDict"
              placeholder="请选择"
              @change="handleAssetsChange"
            >
              <el-option
                v-for="item in warehousingType"
                :key="item.key"
                :label="item.label"
                :value="item.key"
                @click.native="
                  () => {
                    formData.assetsName = item.label
                    assetsType = item.code
                  }
                "
              >
              </el-option>
            </el-select> -->
            <DictSelection
              dictName="类型用途"
              clearable
              v-model="formData.assetDict"
              @itemChange="handleAssetsChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="紧急程度" prop="urgent">
            <el-select
              filterable
              placeholder="请选择"
              class="w100"
              v-model="formData.urgent"
            >
              <el-option
                v-for="item in emergencyState"
                :key="item.code"
                :value="item.code"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <template v-if="formData.isSyncBill == 1">
          <el-col :span="8">
            <el-form-item label="执行部门" prop="executorDeptName">
              <selectTree
                ref="executorDeptRef"
                class="w100"
                :clearable="false"
                :initStr="formData.executorDeptName"
                :options="deptList"
                size="small"
                :props="{
                  value: 'code',
                  label: 'name',
                  children: 'children'
                }"
                @getValue="excuteDeptClick"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="执行人员" prop="executorId">
              <el-select
                filterable
                class="form-ipt"
                style="width: 100%"
                size="small"
                v-model="formData.executorId"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in staffList"
                  :key="item.userId"
                  :label="item.trueName"
                  :value="item.userId"
                  @click.native="
                    () => {
                      formData.executorName = item.trueName;
                    }
                  "
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="8">
          <el-form-item label="锁库盘点" prop="isTreasuryLock">
            <el-switch
              v-model="formData.isTreasuryLock"
              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"
              v-model="formData.remark"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 库外资产台账 -->
      <!-- <Assets
        ref="assetsRef"
        :assetsName="formData.assetsName"
        :assetsType="assetsType"
        :bizType="formData.bizType"
        v-if="formData.bizType === 2"
      /> -->
      <!-- 库内 库存台账 -->
      <AssetsInWarehouse
        ref="assetsRef"
        :assetsName="formData.assetsName"
        :warehouseId="formData.bizTypeId"
        :assetsType="assetsType"
        :bizType="formData.bizType"
      />
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button type="primary" @click="cancel" plain>返回</el-button>
    </div>
  </el-dialog>
</template>

<script>
  // import { isOrNot } from '@/utils/dict/common'
  // import { handleSave, getRuleNameList } from '@/api/stockManagement/stocking'
  // import { warehouseListValuable } from '@/api/stockManagement/warehouseDefinition'
  // import { assetsMap } from './enum'
  // import {
  //   wh_checkStatus,
  //   emergencyState,
  //   warehousingType
  // } from '@/utils/dict/warehouse'
  // import org from '@/api/main/org'
  // import user from '@/api/main/user'
  // import selectTree from '@/components/selectTree'
  // import common from '@/api/common'
  import Assets from './Assets.vue';
  import AssetsInWarehouse from './AssetsInWarehouse.vue';
  // import { getRuleNo } from '@/utils/index'
  export default {
    components: {
      // selectTree,
      Assets,
      AssetsInWarehouse
    },
    data() {
      return {
        // isOrNot,
        // emergencyState,
        // warehousingType,
        // wh_checkStatus,
        isOrNot: [],
        emergencyState: [],
        warehousingType: [],
        ruleNameList: [],
        warehouseList: [],
        wh_checkStatus: [],
        deptList: [],
        auditorList: [],
        staffList: [],
        assetsList: [],
        visible: false,
        type: '新建',
        // assetsType: warehousingType[0].code,
        assetsType: 1,
        formData: {
          bizType: 1,
          assetsName: '',
          assetsId: '',
          deptName: '',
          deptCode: '',
          auditorName: '',
          bizTypeName: '',
          bizTypeId: '',
          ruleId: '',
          isSyncBill: '',
          planName: '',
          // planCode: getRuleNo('PD'),
          verifyUserId: '',
          verifyUserName: '',
          duration: '',
          urgent: '',
          assetDict: '',
          executorDeptCode: '',
          executorDeptName: '',
          isTreasuryLock: 0,
          executorId: '',
          executorName: '',
          remark: ''
        },
        rules: {
          planName: [
            { required: true, message: '请输入计划配置名称', trigger: 'blur' }
          ],
          isSyncBill: [
            { required: true, message: '请选择自动派单', trigger: 'change' }
          ],
          // ruleId: [
          //   { required: true, message: '请选择规则名称 ', trigger: 'change' }
          // ],
          bizType: [
            { required: true, message: '请选择盘点类型', trigger: 'change' }
          ],
          // deptName: [
          //   { required: true, message: '请选择审核部门', trigger: 'blur' }
          // ],
          // verifyUserId: [
          //   { required: true, message: '请选择审核人', trigger: 'blur' }
          // ],
          duration: [
            { required: true, message: '请输入计划盘点时长', trigger: 'blur' }
          ],
          assetDict: [
            { required: true, message: '请选择资产分类', trigger: 'change' }
          ],
          executorDeptName: [
            { required: true, message: '请选择执行部门', trigger: 'change' }
          ],
          executorId: [
            { required: true, message: '请选择执行人员', trigger: 'change' }
          ],
          isTreasuryLock: [
            { required: true, message: '请选择是否锁库盘点', trigger: 'change' }
          ]
        }
      };
    },
    created() {
      // this._getWarehouse()
      // this._getRuleNameList()
      // this._getDeptList()
      //this._getEnumDefinitionList();
    },

    methods: {
      open(type = '新建') {
        this.type = type;
        this.visible = true;
      },
      cancel() {
        this.$refs.formRef.resetFields();
        this.$refs.executorDeptRef && this.$refs.executorDeptRef.clearHandle();
        this.$refs.deptRef && this.$refs.deptRef.clearHandle();
        this.$refs.assetsRef && this.$refs.assetsRef.resetData();
        this.assetsType = '';
        this.formData.assetsName = '';
        this.visible = false;
      },
      // 参数处理
      getParams() {
        const { classificationList = [], tableSelectionList = [] } =
          (this.$refs.assetsRef && this.$refs.assetsRef.getSelectList()) || {};

        const tableMap = assetsMap[this.formData.assetsName];

        return {
          ...this.formData,
          classificationList: classificationList.map((i) => ({
            classificationID: i.id,
            classificationName: i.name
          })),
          planInventoryDetailList: tableSelectionList.map((item) => {
            return {
              informationId: item.id,
              bizTypeId: item.bizTypeId,
              assetCode: item.informationCode,
              assetName: item.informationName,
              assetBrand: item.brandNum,
              specification: item.specification,
              assetSku: item.modelType,
              minPackUnit: item.packingUnit,
              takeStockPattern: item.takeStockPattern,
              univalence: item.univalence,
              univalenceUnit: item.univalenceUnit,
              isUnpack: item.isUnpack,
              unit: item.measuringUnit
            };
            // if (this.formData.bizType == 2) {
            //   const obj = {
            //     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)}`,
            //     assetTypeDict: this.formData.assetDict,
            //     bizTypeId: item.bizTypeId,
            //     bizTypeName: item.bizTypeName,
            //   };

            //   for (const key in tableMap) {
            //     obj[key] = item[tableMap[key]];
            //   }
            //   return obj;
            // } else {
            //   return {
            //     ...item,
            //     assetsId: item.assetSubType,
            //     realInventoryNum: item.inventorySum,
            //     assetBrand: item.brand,
            //     assetSku: item.model,
            //     minPackUnit: item.minPackUtil,
            //     unit: item.basePackUtil,
            //     materialType: item.assetType,
            //   };
            // }
          }),
          cycleType: 2,
          planType: 'INVENTORY'
        };
      },
      initLocation(inp) {
        return inp ? inp + ',' : '';
      },
      async submit() {
        this.$refs.formRef.validate(async (value) => {
          if (value) {
            const params = this.getParams();

            if (
              !(
                params.classificationList.length ||
                params.planInventoryDetailList.length
              )
            ) {
              return this.$message.error('请选择资产分类台账！');
            }

            const res = await handleSave(params);

            if (res?.success) {
              this.$message.success('保存成功！');

              this.$emit('success');
              this.cancel();
            }
          }
        });
      },
      async _getDeptList() {
        let res = await org.tree();
        if (res?.success) {
          this.deptList = res.data;
        }
      },
      handleAssetsChange(item) {
        this.formData.assetsName = item.dictValue;
        this.assetsType = item.dictCode;
        this.$nextTick(
          () =>
            this.$refs.assetsRef && this.$refs.assetsRef.handleAssetsChange()
        );
      },
      // 执行部门 点击事件
      async excuteDeptClick(data) {
        this.formData.executorDeptCode = data?.code;
        this.formData.executorDeptName = data?.name;
        this.formData.executorId = '';
        this.formData.executorName = '';
        if (data) {
          this.$refs.formRef.validateField('executorDeptName');
          this._getUserList(data.code).then((res) => {
            if (data.code === this.formData.executorDeptCode) {
              this.staffList = res;
            }
          });
        }
      },
      // 审核部门 点击事件
      async auditorDeptClick(data) {
        this.formData.deptCode = data?.code;
        this.formData.deptName = data?.name;
        this.formData.verifyUserId = '';
        this.formData.verifyUserName = '';
        if (data) {
          this.$refs.formRef.validateField('deptName');

          this._getUserList(data.code).then((res) => {
            if (data.code === this.formData.deptCode) {
              this.auditorList = res;
            }
          });
        }
      },

      _getUserList(deptCode) {
        return new Promise(async (resolve) => {
          let res = await user.list({ deptCode, size: 99999 });
          if (res?.success) {
            resolve(res.data.items);
          }
        });
      },
      async _getEnumDefinitionList() {
        let res = await common.getEnumDefinitionList({ key: 'ASSECTSTYPE' });
        if (res?.success) {
          this.assetsList = res.data;
        }
      },

      async _getWarehouse() {
        const res = await warehouseListValuable();
        if (res?.success) {
          this.warehouseList = res.data.filter((i) => !!i.status);
        }
      },
      async _getRuleNameList() {
        const res = await getRuleNameList({ ruleTypeEm: 'INVENTORY' });
        if (res?.success) {
          this.ruleNameList = res.data || [];
        }
      }
    }
  };
</script>
<style lang="scss" scoped>
  ::v-deep.temporary-dialog {
    .el-form-item {
      margin-bottom: 20px !important;
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
