<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="6">
          <el-form-item label="编码" prop="code">
            <el-input
              v-model="addForm.code"
              placeholder="自动生成"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <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="6">
          <el-form-item label="审核人" prop="approvalUserId">
            <el-select
              v-model="addForm.approvalUserId"
              size="small"
              style="width: 100%"
              @change="changeApprovalUser"
              :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="6">
          <el-form-item label="报损报溢部门" prop="executeGroupId">
            <deptSelect
              :isBindPlan="isBindPlan"
              v-model="addForm.executeGroupId"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <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="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-button
          v-if="!isBindPlan"
          style="margin-left: 10px"
          type="primary"
          @click="addProducts"
          >选择工单</el-button
        >
      </HeaderTitle>
      <el-table
        ref="table"
        :data="productList"
        :max-height="500"
        row-key="id"
        tooltip-effect="dark"
        border
      >
        <el-table-column width="55px" label="序号" type="index">
        </el-table-column>
        <el-table-column
          prop="code"
          label="盘点单号"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="planName"
          label="计划名称"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="产品分类" width="180">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="right">
              <el-table
                :data="scope.row.planDetailVOList"
                :max-height="500"
                border
              >
                <el-table-column label="序号" type="index" width="50">
                </el-table-column>
                <el-table-column
                  label="状态"
                  prop="status"
                  :show-overflow-tooltip="true"
                >
                  <template slot-scope="{ row }">
                    {{
                      row.status > 0
                        ? statusOption.filter(
                            (item) => item.value == row.status
                          )[0].label
                        : ''
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="数量" :show-overflow-tooltip="true">
                  <template slot-scope="{ row }">
                    {{
                      row.status > 0
                        ? row[
                            statusOption.filter(
                              (item) => item.value == row.status
                            )[0].numKey
                          ]
                        : 0
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  width="150"
                  label="物品名称"
                  prop="categoryName"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                  label="批次号"
                  prop="batchNo"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                  width="150"
                  label="包装编码"
                  prop="packageNo"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                  label="包装数量"
                  prop="info.packingCountBase"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                  label="包装单位"
                  prop="info.packingUnit"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                  label="重量"
                  prop="info.weight"
                  :show-overflow-tooltip="true"
                >
                </el-table-column>
                <el-table-column
                  label="重量单位"
                  prop="info.weightUnit"
                  :show-overflow-tooltip="true"
                >
                </el-table-column>
                <el-table-column
                  width="200"
                  label="仓库"
                  prop="info.warehouseName"
                  :show-overflow-tooltip="true"
                ></el-table-column>
              </el-table>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.categoryLevelId }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          prop="warehouseName"
          label="盘点仓库"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="executeGroupName"
          label="盘点部门"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="executorName"
          label="盘点人员"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="surplusQuantity"
          label="盘盈数量"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="wornQuantity"
          label="盘亏数量"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="loseQuantity"
          label="破损数量"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="盘点审核时间"
          :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>
      <div v-if="addForm.status != 0" style="height: 350px">
        <HeaderTitle title="流程图" size="16px"></HeaderTitle>
        <div style="height: calc(100% - 40px);">
          <my-process-viewer
            key="designer"
            v-model="bpmnXML"
            v-bind="bpmnControlForm"
            :activityData="activityList"
            :processInstanceData="processInstance"
            :taskData="tasks"
          />
        </div>
      </div>
    </el-form>
    <div v-if="!isBindPlan" slot="footer">
      <el-button
        v-if="addForm.status == 0"
        type="primary"
        size="small"
        @click="submit"
        >提交</el-button
      >
      <el-button type="primary" size="small" @click="config(false)"
        >保存</el-button
      >
      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
    <div v-else slot="footer">
      <el-button
        v-if="addForm.status == 0"
        type="primary"
        size="small"
        @click="submit"
        >提交</el-button
      >
      <el-button type="primary" size="small" @click="dialogVisible = false"
        >确定</el-button
      >
      <el-button size="small" @click="dialogVisible = false">关闭</el-button>
    </div>
    <reportProcuts
      :visibleDialog.sync="visibleDialog"
      :treeIds="productType"
      :dimension="dimension"
      :statusOption="statusOption"
      :warehouseId="addForm.warehouseId"
      :selectionIds="selectionIds"
      :loadTree.sync="loadTree"
      @selectTableData="addGoods"
    />
  </el-dialog>
</template>

<script>
  import {
    getProcessInstance,
    getTaskListByProcessInstanceId,
    getProcessDefinitionBpmnXML,
    getActivityList
  } from '@/api/bpm/index';
  import { getTreeByGroup } from '@/api/classifyManage';
  import reportProcuts from './reportProcuts.vue';
  import { getCode } from '@/api/codeManagement';
  import {
    getReportPlanDetailById,
    saveReportsList,
    updateReportsList
  } 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,
      reportProcuts
    },
    data() {
      return {
        // 流程实例
        processId: undefined, // 流程实例的编号
        processInstance: {},
        // BPMN 数据
        bpmnXML: null,
        bpmnControlForm: {
          prefix: 'flowable'
        },
        activityList: [],
        // 审批记录
        tasksLoad: true,
        tasks: [],
        processInstanceLoading: false,
        statusOption: [
          {
            label: '盘盈',
            value: '2',
            numKey: 'surplusQuantity'
          },
          {
            label: '丢失',
            value: '3',
            numKey: 'loseQuantity'
          },
          {
            label: '破损',
            value: '4',
            numKey: 'wornQuantity'
          }
        ],
        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: {
          name: '', // 规则名称
          code: '', // 计划配置单号
          name: '', // 计划配置名称
          executeGroupId: '', // 执行部门code
          executeGroupName: '', // 执行部门name
          executorId: '', // 执行人id
          executorName: '', // 执行人name
          warehouseId: '', // 盘点仓库Id
          remark: '', // 备注
          status: 0, // 状态(待审核)
          approvalUserId: '', // 审核人Id
          approvalUserName: '' // 审核人name
        },
        rules: {
          code: [
            { required: true, message: '请输入计划配置单号', trigger: 'blur' }
          ],
          name: [
            { 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.getOrderCode();
          if (
            this.dialogTile === '修改报损报溢' ||
            this.dialogTile === '报损报溢详情'
          ) {
            getReportPlanDetailById(this.id).then(async (res) => {
              this.addForm = res;
              if (this.addForm.executeGroupId) {
                this.getUserList({ groupId: this.addForm.executeGroupId });
              }
              this.productList = res.info;
              if (this.addForm.status != 0) {
                this.getDetail(res.flowableId);
              }
            });
          } else {
            this.productList = [];
            this.addForm = {
              name: '', // 规则名称
              code: '', // 计划配置单号
              executeGroupId: '', // 执行部门code
              executeGroupName: '', // 执行部门name
              executorId: '', // 执行人id
              executorName: '', // 执行人name
              warehouseId: '', // 盘点仓库Id
              remark: '', // 备注
              status: 0, // 状态(待审核)
              approvalUserId: '', // 审核人Id
              approvalUserName: '' // 审核人name
            };
          }
        }
      }
    },
    computed: {
      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      },
      selectionIds() {
        return this.productList.map((item) => item.categoryId);
      }
    },
    methods: {
      /** 获得流程实例 */
      getDetail(id) {
        // 获得流程实例相关
        this.processInstanceLoading = true;
        getProcessInstance(id).then((response) => {
          if (!response) {
            this.$message.error('查询不到流程信息！');
            return;
          }
          // 设置流程信息
          this.processInstance = response;

          // //将业务表单，注册为动态组件
          // const path = this.processInstance.processDefinition.formCustomViewPath;
          // Vue.component("async-biz-form-component", function (resolve) {
          //   require([`@/views${path}`], resolve);
          // });
          // 加载流程图
          getProcessDefinitionBpmnXML(
            this.processInstance.processDefinition.id
          ).then((response) => {
            this.bpmnXML = response;
          });
          // 加载活动列表
          getActivityList({
            processInstanceId: this.processInstance.id
          }).then((response) => {
            console.log(response, 'response');
            this.activityList = response;
          });

          // 取消加载中
          this.processInstanceLoading = false;
        });

        // 获得流程任务列表（审批记录）
        this.tasksLoad = true;
        getTaskListByProcessInstanceId(id).then((response) => {
          // 审批记录
          this.tasks = [];
          // 移除已取消的审批
          response.forEach((task) => {
            if (task.result !== 4) {
              this.tasks.push(task);
            }
          });
          // 排序，将未完成的排在前面，已完成的排在后面；
          this.tasks.sort((a, b) => {
            // 有已完成的情况，按照完成时间倒序
            if (a.endTime && b.endTime) {
              return b.endTime - a.endTime;
            } else if (a.endTime) {
              return 1;
            } else if (b.endTime) {
              return -1;
              // 都是未完成，按照创建时间倒序
            } else {
              return b.createTime - a.createTime;
            }
          });

          // 需要审核的记录
          const userId = store.getters.userId;
          this.tasks.forEach((task) => {
            if (task.result !== 1 && task.result !== 6) {
              // 只有待处理才需要
              return;
            }
            if (!task.assigneeUser || task.assigneeUser.id !== userId) {
              // 自己不是处理人
              return;
            }
          });

          // 取消加载中
          this.tasksLoad = false;
        });
      },
      // 添加物品明细
      async addGoods(data) {
        console.log(data);
        let productList = data.map((item) => {
          return {
            ...item
          };
        });
        console.log('productList------', productList);
        this.productList = this.productList.concat(productList);
      },
      addProducts() {
        this.visibleDialog = true;
      },
      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('plan_profit_loss');
        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 = {
          name: '', // 规则名称
          code: '', // 计划配置单号
          executeGroupId: '', // 执行部门code
          executeGroupName: '', // 执行部门name
          executorId: '', // 执行人id
          executorName: '', // 执行人name
          warehouseId: '', // 盘点仓库Id
          remark: '', // 备注
          status: 0, // 状态(待审核)
          approvalUserId: '', // 审核人Id
          approvalUserName: '' // 审核人name
        };
      },

      // 封装 - 获取盘点仓库
      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) {}
      },
      submit() {
        this.config(true);
      },
      config(isProcess) {
        console.log(this.addForm);
        console.log('isProcess------------', isProcess);
        this.$refs.addFormRef.validate(async (valid) => {
          let res = null;
          if (valid) {
            let params = {
              ...this.addForm,
              info: this.productList
            };
            if (isProcess) {
              params.status = 1;
            } else {
              params.status = 0;
            }
            if (this.productList?.length > 0) {
              if (this.dialogTile === '修改报损报溢') {
                res = await updateReportsList(params);
              } else {
                res = await saveReportsList(params);
              }
            } else {
              return this.$message.error('请选择报损工单物品信息');
            }

            if (res.code == 0) {
              this.handleClose();
              this.$message.success(res.message);
              this.$emit('refreshList');
            }
          }
        });
      },
      handleChangeassetDict(data) {
        console.log(data);
      }
    }
  };
</script>

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