<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.code"
              placeholder="自动生成"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划配置名称" prop="planRuleName">
            <el-input
              v-model="addForm.planRuleName"
              placeholder="请输入"
               :disabled="isBindPlan"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="自动派单" prop="isSyncBill">
            <el-select
              v-model="addForm.isSyncBill"
              class="w100"
              placeholder="请选择"
               :disabled="isBindPlan"
			   filterable
            >
              <el-option :value="true" label="是"></el-option>
              <el-option :value="false" 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="请选择规则名称"
               :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="bizType">
            <el-select
              v-model="addForm.bizType"
              class="w100"
              placeholder="请选择"
              @change="chooseType"
               :disabled="isBindPlan"
			  filterable
            >
              <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="
              addForm.bizType == 1
                ? [
                    {
                      required: true,
                      message: '请选择资产类别',
                      trigger: ['blur', 'change']
                    }
                  ]
                : []
            "
          >
            <el-select
              placeholder="请选择"
              class="w100"
              v-model="addForm.bizTypeId"
              :disabled="addForm.bizType == 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="资产分类" prop="assetDict">
            <DictSelection dictName="类型用途" clearable filterable v-model="addForm.assetDict">
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="addForm.isSyncBill">
          <el-form-item label="执行部门" prop="executorDeptCode">
				    <deptSelect v-model="addForm.executorDeptCode" @changeGroup="searchDeptNodeClick"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="addForm.isSyncBill">
          <el-form-item label="执行人员" prop="executorId">
			  <el-select
			    v-model="addForm.executorId"
			    size="small"
			    style="width: 100%"
			    :disabled="isBindPlan"
				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 :span="8">
          <el-form-item label="紧急程度" prop="urgent">
			  <DictSelection dictName="紧急程度" clearable filterable v-model="addForm.urgent">
			  </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="锁库盘点" prop="isTreasuryLock">
            <el-switch
              v-model="addForm.isTreasuryLock"
              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="status">
            <el-switch
              v-model="addForm.status"
              active-text="开"
              inactive-text="关"
              :active-value="true"
              :inactive-value="false"
            ></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>
      <!-- 库外 -->
      <!-- <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.bizType"
        :planRuleInventoryDetailList="planRuleInventoryDetailList"
        :isBindPlan = "isBindPlan"
      />
    </el-form>
    <div slot="footer">
      <el-button type="primary" size="small" @click="submit">提交</el-button>
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
// import { wh_checkStatus} from '@/utils/dict/warehouse'
import { getCode , getWarehouseList } from '@/api/ruleManagement/matter';
import AssetsInWarehouse from './AssetsInWarehouse'
import { getRule } 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
      }
    },
  },
  components: { 
	deptSelect,
    AssetsInWarehouse 
  },
  data () {
    return {
	  addDialogLoading:false,
      dialogVisible: false,
      wh_checkStatus:[], // 盘点类型
      warehouseList: [], // 盘点仓库
      uerList: [], // 审核人
      executorList: [], // 执行人
      assetsType: null,
      planRuleInventoryDetailList: [],
      addForm: {
        code: '', // 计划配置单号
        planRuleName: '', // 计划配置名称
        isSyncBill: true, // 是否自动派单
        ruleId: '', // 规则名称
        bizType: '', // 盘点类型
        bizTypeId: '', // 盘点仓库Id
        bizTypeName: '', // 盘点仓库name
        verifyUserId: '', // 审核人Id
        verifyUserName: '', // 审核人name
        duration: null, // 盘点时长
        assetDict: '', // 资产分类id
        assetsName: '', // 资产分类name
        urgent: null, // 紧急程度
        executorDeptCode: '', // 执行部门code
        executorDeptName: '', // 执行部门name
        executorId: '', // 执行人id
        executorName: '', // 执行人name
        isTreasuryLock: false, // 是否锁库盘点
        status: true, // 状态
        remark: '' // 备注
      },
      rules: {
        planRuleName: [
          { required: true, message: '请输入计划配置名称', trigger: 'blur' }
        ],
        isSyncBill: [
          { required: true, message: '请选择是否自动派单', trigger: 'change' }
        ],
        ruleId: [
          { required: true, message: '请选择规则名称', trigger: 'change' }
        ],
        duration: [
          { required: true, message: '请输入计划完成时长', trigger: 'blur' }
        ],
        bizType: [
          { required: true, message: '请选择盘点类型', trigger: 'change' }
        ],
        bizTypeId: [
          { required: true, message: '请选择盘点仓库', trigger: 'change' }
        ],
        verifyUserId: [
          { required: false, message: '请选择审核人', trigger: 'change' }
        ],
        executorDeptCode: [
          { 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()
      }
    },
    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.executorDeptCode, 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: {
    // ...mapGetters([
    //   'equipmentList',
    //   // 'ruleNameList',
    //   'planRulesDetails',
    //   'addDialogLoading',
    //   'addOrUpdate'
    // ])
  },
  methods: {
    // 获取规则名列表
    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, 'code', code);
	}, 
    // 关闭弹窗
    handleClose () {
      this.dialogVisible = false
      this.$refs.addFormRef.resetFields()
      if (this.$refs.searchTree) {
        this.$refs.searchTree.clearHandle()
      }
      if (this.addForm.bizType == 2) {
        this.$refs.assetsRef._clearTreeTableData()
      }
      this.addForm.assetsName = ''
      this.assetsType = null
      this.addForm = {
        code: '', // 计划配置单号
        planRuleName: '', // 计划配置名称
        isSyncBill: null, // 是否自动派单
        ruleId: '', // 规则名称
        bizType: '', // 盘点类型
        bizTypeId: '', // 盘点仓库Id
        bizTypeName: '', // 盘点仓库name
        verifyUserId: '', // 审核人Id
        verifyUserName: '', // 审核人name
        duration: null, // 盘点时长
        assetDict: '', // 资产分类id
        assetsName: '', // 资产分类name
        urgent: null, // 紧急程度
        executorDeptCode: '', // 执行部门code
        executorDeptName: '', // 执行部门name
        executorId: '', // 执行人id
        executorName: '', // 执行人name
        isTreasuryLock: false, // 是否锁库盘点
        status: true, // 状态
        remark: '' // 备注
      }
    },

    // 封装 - 获取盘点仓库
    async _getWarehouse () {
	  const params =  {  pageNum: 1 ,size:-1 }
      const res = await getWarehouseList(params)
	  this.warehouseList = res.list
    },

    //选择部门(搜索)
    searchDeptNodeClick (info) {
      if (info) {
		   const params = { groupId: info }
		   this.getUserList(params)
      } else {
        this.addForm.executorDeptCode = 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.bizType === 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.bizTypeId = null
        this.addForm.bizTypeName = null
      }
    },

    // 提交
    submit () {
      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('请选择资产分类台账！')
              }
          }
          const res = await planRules.handleSaveOrUpdate(params)
          if (res?.success) {
            this.handleClose()
            this.$message.success('保存成功！')
            this.$emit('refreshList')
          }
        }
      })
    },
    handleChangeassetDict(data){
        console.log(data)
    }
  }
}
</script>

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