<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%"
  >
    <HeaderTitle title="基本信息" size="16px"></HeaderTitle>
    <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="name">
            <el-input
              :disabled="isBindPlan"
              v-model="addForm.name"
              placeholder="请输入"
            ></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="executorDuration">
            <el-input
              v-model.number="addForm.executorDuration"
              placeholder="请输入"
              :disabled="isBindPlan"
            >
              <template #suffix>分钟</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :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="approvalUserId">
            <el-select
              v-model="addForm.approvalUserId"
              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="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 :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="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>
      <HeaderTitle title="盘点物品信息" size="16px">
        <el-select
          :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-button
          v-if="!isBindPlan"
          style="margin-left: 10px"
          type="primary"
          @click="addProducts"
          >添加物品</el-button
        >
      </HeaderTitle>
      <el-table
        ref="table"
        :data="productList"
        :height="500"
        row-key="id"
        tooltip-effect="dark"
        border
      >
        <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
          width="150"
          prop="categoryLevelPath"
          label="产品分类"
          :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-column v-if="!isBindPlan" label="操作" width="100">
          <template slot-scope="{ row, $index }">
            <el-button @click="deleted(row, $index)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </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>
    <selectType
      :visibleDialog.sync="visibleDialog"
      :treeIds="productType"
      :dimension="dimension"
      :warehouseId="addForm.warehouseId"
      :selectionIds="selectionIds"
      :loadTree.sync="loadTree"
      @selectTableData="addGoods"
    />
  </el-dialog>
</template>

<script>
  import { getTreeByGroup } from '@/api/classifyManage';
  import selectType from './selectType.vue';
  import { getCode } from '@/api/codeManagement';
  import {
    getInventoryPlanDetailById,
    saveInventoryPlan,
    updateInventoryPlan
  } from '@/api/inventory';
  import {
    getRule,
    getWarehouseList,
    getCategoryLevelIdByWarehouseId
  } from '@/api/ruleManagement/plan';
  import { getUserPage } from '@/api/system/organization';
  import deptSelect from '@/components/CommomSelect/new-dept-select.vue';
  export default {
    props: {
      dialogTile: {
        type: String,
        default: '新增临时盘点计划'
      },
      isBindPlan: {
        type: Boolean,
        default: function () {
          return false;
        }
      },
      id: {
        type: String,
        default: ''
      }
    },
    components: {
      deptSelect,
      selectType
    },
    data() {
      return {
        visibleDialog: false,
        type: 2, // 盘点类型 2仓储 4资产
        dimension: 1, // 盘点维度1物品 2批次
        factoryOptions: [],
        workshopOptions: [],
        productionLineOptions: [],
        stationOptions: [],
        codeList: [],
        addDialogLoading: false,
        dialogVisible: false,
        wh_checkStatus: [], // 盘点类型
        warehouseList: [], // 盘点仓库
        uerList: [], // 审核人
        executorList: [], // 执行人
        assetsType: null,
        planRuleInventoryDetailList: [],
        tableList: [],
        newColumns: [],
        selection: [],
        keyWord: '',
        total: 0,
        page: 1,
        size: 10,
        loadTree: true,
        productList: [],
        productType: [],
        addForm: {
          ruleId: '', // 规则名称
          ruleName: '', // 规则名称
          code: '', // 计划配置单号
          name: '', // 计划配置名称
          executeGroupId: '', // 执行部门code
          executeGroupName: '', // 执行部门name
          executorId: '', // 执行人id
          executorName: '', // 执行人name
          lockWarehouse: 1, // 是否锁库盘点
          urgent: '1', // 紧急程度
          warehouseId: '', // 盘点仓库Id
          autoOrder: 1, // 是否自动派单
          remark: '', // 备注
          approvalUserId: '', // 审核人Id
          approvalUserName: '', // 审核人name
          executorDuration: 0 // 盘点时长
        },
        rules: {
          code: [
            { required: true, message: '请输入计划配置单号', trigger: 'blur' }
          ],
          name: [
            { required: true, message: '请输入计划配置名称', trigger: 'blur' }
          ],
          autoOrder: [
            { required: true, message: '请选择是否自动派单', trigger: 'change' }
          ],
          ruleId: [
            { required: true, message: '请选择规则名称', trigger: 'change' }
          ],
          executorDuration: [
            { required: true, message: '请输入计划完成时长', trigger: 'blur' }
          ],
          warehouseId: [
            { required: true, message: '请选择盘点仓库', trigger: 'change' }
          ],
          executeGroupId: [
            { required: true, message: '请选择选择执行部门', trigger: 'change' }
          ],
          executorId: [
            { required: true, message: '请选择选择执行人员', trigger: 'change' }
          ]
        },
        ruleNameList: []
      };
    },
    watch: {
      dialogVisible(val) {
        if (val) {
          // 获取审核人列表数据
          this.getUserList();
          // 获取盘点仓库
          this._getWarehouse();
          // 获取计划单号
          this.getOrderCode();
          // 获取规则名称
          this._getRuleNameList();
          // 获取物品类型
          this.getGoodsList();
          if (
            this.dialogTile === '修改临时盘点计划' ||
            this.dialogTile === '临时盘点计划详情'
          ) {
            getInventoryPlanDetailById(this.id).then(async (res) => {
              res.urgent = String(res.urgent);
              this.addForm = res;
              this.dimension = res.planDetailVOS[0].batchNo ? 2 : 1;
              if (this.addForm.executeGroupId) {
                this.getUserList({ groupId: this.addForm.executeGroupId });
              }
              this.productList = res.planDetailVOS.map((item) => item.info);
              getCategoryLevelIdByWarehouseId({
                warehouseId: this.addForm.warehouseId
              }).then((data) => {
                console.log(data);
                this.productType = Array.from(new Set(data));
              });
            });
          } else {
            this.productList = [];
            this.addForm = {
              ruleId: '', // 规则名称
              ruleName: '', // 规则名称
              code: '', // 计划配置单号
              executeGroupId: '', // 执行部门code
              executeGroupName: '', // 执行部门name
              executorId: '', // 执行人id
              executorName: '', // 执行人name
              lockWarehouse: 1, // 是否锁库盘点
              urgent: '1', // 紧急程度
              warehouseId: '', // 盘点仓库Id
              autoOrder: 1, // 是否自动派单
              remark: '', // 备注
              approvalUserId: '', // 审核人Id
              approvalUserName: '', // 审核人name
              executorDuration: 0 // 盘点时长
            };
          }
        }
      }
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      selectionIds() {
        return this.productList.map((item) => item.categoryId);
      }
    },
    methods: {
      // 添加物品明细
      async addGoods(data) {
        console.log(data);
        let productList = data.map((item) => {
          return {
            ...item
          };
        });
        this.productList = this.productList.concat(productList);
      },
      addProducts() {
        if (this.addForm.warehouseId) {
          console.log(this.addForm.warehouseId);
          this.visibleDialog = true;
        } else {
          this.$message.warning('请选择盘点仓库');
        }
      },
      deleted(row, index) {
        this.productList.splice(index, 1);
      },
      selecctedRow(val) {
        this.selection = val;
      },
      dimensionChange() {
        this.productList = [];
      },
      checkSelectable(row) {
        return true;
      },
      // 改变规则名称
      change_ruleId(val) {
        this.addForm.ruleName = this.ruleNameList.filter(
          (item) => item.id === val
        )[0].name;
      },
      // 获取物品类型列表
      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, 'code', 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.productList = [];
          getCategoryLevelIdByWarehouseId({ warehouseId: val }).then((data) => {
            console.log(data);
            this.productType = Array.from(new Set(data));
          });
        }
      },
      // 关闭弹窗
      handleClose() {
        this.dialogVisible = false;
        this.$refs.addFormRef.resetFields();
        this.addForm.assetsName = '';
        this.assetsType = null;
        this.addForm = {
          ruleId: '', // 规则名称
          ruleName: '', // 规则名称
          code: '', // 计划配置单号
          executeGroupId: '', // 执行部门code
          executeGroupName: '', // 执行部门name
          executorId: '', // 执行人id
          executorName: '', // 执行人name
          lockWarehouse: 1, // 是否锁库盘点
          urgent: '1', // 紧急程度
          warehouseId: '', // 盘点仓库Id
          autoOrder: 1, // 是否自动派单
          remark: '', // 备注
          approvalUserId: '', // 审核人Id
          approvalUserName: '', // 审核人name
          executorDuration: 0 // 盘点时长
        };
      },

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

      //选择部门(搜索)
      searchDeptNodeClick(info, row) {
        console.log(info);
        console.log(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) {}
      },
      submit() {
        console.log(this.addForm);
        this.$refs.addFormRef.validate(async (valid) => {
          let res = null;
          if (valid) {
            let params = {
              ...this.addForm,
              planDetailAddPOList: this.productList.map((item) => {
                return {
                  batchNo: item.batchNo,
                  categoryId: item.categoryId,
                  categoryName: item.categoryName,
                  info: item
                };
              })
            };
            if (this.productList?.length > 0) {
              if (this.dialogTile === '修改临时盘点计划') {
                res = await updateInventoryPlan(params);
              } else {
                res = await saveInventoryPlan(params);
              }
            } else {
              return this.$message.error('请选择需要盘点物品');
            }

            if (res.code == 0) {
              this.handleClose();
              console.log(res.message);

              this.$message.success({
                message:res.message,
                duration:2000
              });
              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>
