<template>
  <ele-modal
    width="80%"
    :visible="visible"
    v-if="visible"
    append-to-body
    custom-class="ele-dialog-form"
    :title="title"
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :maxable="true"
  >
    <header-title title="基本信息"></header-title>
    <el-form
      ref="addFormRef"
      :model="addForm"
      :rules="addFormRules"
      label-width="120px"
      v-loading="loading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="计划配置单号" prop="code">
            <el-input
              v-model="addForm.code"
              size="small"
              placeholder="自动带出"
              disabled
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="计划配置名称" prop="name">
            <el-input
              v-model="addForm.name"
              size="small"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="自动派单" prop="autoOrder">
            <el-select
              v-model="addForm.autoOrder"
              size="small"
              style="width: 100%"
              @change="autoOrderChange"
            >
              <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="duration">
            <div style="display: flex">
              <el-input
                type="number"
                v-model="addForm.duration"
                size="small"
                placeholder="请输入"
                @input="formDataDurationTime"
              >
                <template #suffix>分钟</template>
              </el-input>
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="部门" prop="groupId">
            <deptSelect
              v-model="addForm.groupId"
              @changeGroup="searchDeptNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="负责人" prop="executorId">
            <el-select
              v-model="addForm.executorId"
              size="small"
              style="width: 100%"
              multiple
              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="approvalUserId">
            <el-select
              v-model="addForm.approvalUserId"
              size="small"
              clearable
              style="width: 100%"
              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
              dictName="紧急程度"
              clearable
              v-model="addForm.urgent"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              resize="none"
              v-model="addForm.remark"
              :rows="2"
              placeholder="请详细说明"
              size="small"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-tabs type="card">
        <el-tab-pane v-if="ruleInfo" :label="ruleInfo.name">
          <div class="el-tab_box">
            <div class="equipmentList_box">
              <header-title title="设备列表"> </header-title>
              <el-table :data="deviceList" border>
                <el-table-column label="序号" type="index" width="50">
                </el-table-column>
                <el-table-column label="设备名称" align="center" prop="name">
                  <template slot-scope="{ row }">
                    <template>
                      {{ row.name }}
                    </template>
                  </template>
                </el-table-column>
                <el-table-column label="编号" align="center" prop="codeNumber">
                  <template slot-scope="{ row }">
                    <template>
                      {{ row.codeNumber }}
                    </template>
                  </template>
                </el-table-column>
                <el-table-column label="固资编码" align="center" prop="fixCode">
                  <template slot-scope="{ row }">
                    <template>
                      {{ row.fixCode }}
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="ruleMatters_box">
              <header-title title="规则事项">
                <div>
                  <el-button
                    v-if="productionInfo.executeStatus == 0"
                    size="small"
                    icon="el-icon-plus"
                    class="ele-btn-icon"
                    type="primary"
                    @click="addPostscript"
                    >新增</el-button
                  >
                </div>
              </header-title>
              <el-table v-if="ruleInfo" :data="ruleInfo.ruleItems" border>
                <el-table-column label="序号" width="50">
                  <template slot-scope="scope">
                    <span>{{ scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="零部件编码"
                  prop="categoryCode"
                  width="150"
                >
                  <template slot-scope="scope">
                    <div v-if="scope.row.isNew">
                      <el-input
                        v-model="scope.row.categoryCode"
                        placeholder="请输入零部件编码"
                      ></el-input>
                    </div>
                    <div v-else>
                      <span>{{ scope.row.categoryCode }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="零部件名称" prop="categoryName">
                  <template slot-scope="scope">
                    <div v-if="scope.row.isNew">
                      <el-input
                        v-model="scope.row.categoryName"
                        placeholder="请输入零部件名称"
                      ></el-input>
                    </div>
                    <div v-else>
                      <span>{{ scope.row.categoryName }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="事项" prop="name">
                  <template slot-scope="scope">
                    <div v-if="scope.row.isNew">
                      <el-input
                        v-model="scope.row.name"
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                    <div v-else>
                      <span>{{ scope.row.name }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="内容" prop="content">
                  <template slot-scope="scope">
                    <div v-if="scope.row.isNew">
                      <el-input
                        v-model="scope.row.content"
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                    <div v-else>
                      <span>{{ scope.row.content }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作指导" prop="operationGuide">
                  <template slot-scope="scope">
                    <div
                      class="operationGuide_box"
                      @click="
                        openOperationGuideDialogDialog(
                          scope.row.operationGuide,
                          scope.$index
                        )
                      "
                    >
                      <div class="left_content">
                        <template v-if="scope.row.operationGuide">
                          <div
                            v-for="(item, index) in scope.row.operationGuide
                              .toolList"
                            :key="item.id"
                            >{{ index + 1 }}.{{ item.name }}</div
                          >
                        </template>
                      </div>
                      <div class="right_content">
                        <template v-if="scope.row.operationGuide">
                          <div
                            v-for="(item, index) in scope.row.operationGuide
                              .procedureList"
                            :key="item.id"
                            >{{ index + 1 }}.{{ item.content }}</div
                          >
                        </template>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="标准" prop="norm" width="100">
                  <template slot-scope="scope">
                    <div v-if="scope.row.isNew">
                      <el-input
                        v-model="scope.row.norm"
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                    <div v-else>
                      <span>{{ scope.row.norm }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button
                      v-if="productionInfo.executeStatus == 0"
                      type="text"
                      @click="deleteItem(scope.$index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template v-slot:footer>
      <el-button :loading="butLoading" @click="beforeClose">取消</el-button>
      <el-button
        v-if="$hasPermission('mes:producetaskrulerecord:save')"
        type="primary"
        @click="submit"
        :disabled="productionInfo.executeStatus != 0"
        :loading="butLoading"
      >
        派单</el-button
      >
    </template>

    <OperationGuideDialog
      ref="operationGuideDialog"
      @save="saveEdit"
    ></OperationGuideDialog>
  </ele-modal>
</template>

<script>
  import { getDetail, getCode } from '@/api/ruleManagement/matter';
  import { getUserPage } from '@/api/system/organization';
  import OperationGuideDialog from './operationGuideDialog.vue';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import { getById } from '@/api/maintenance/patrol_maintenance';
  import { getFile } from '@/api/system/file';
  import { getAssetInfo } from '@/api/produce/device';
  import {
    saveRuleRecord,
    tempSaveOrUpdateAndSubmit
  } from '@/api/producetaskrulerecord/index.js';

  export default {
    components: {
      deptSelect,
      OperationGuideDialog
    },
    emits: ['reload'],
    props: {
      isTempRecord: {
        type: Number,
        default: 0
      }
    },
    data() {
      const formData = {
        id: null,
        code: '', // 计划配置单号
        name: '', // 计划配置名称
        autoOrder: 1, // 自动派单
        ruleId: '', // 规则id
        ruleName: '', // 规则名称
        duration: null, // 计划完成时长
        categoryId: '', // 设备类别id
        approvalUserId: '', // 审核人id
        groupId: '', // 巡点检部门code
        executorId: [], // 巡点检人员id
        executorPhone: '',
        status: 1, // 状态
        remark: '', // 备注
        urgent: '1', // 紧急程度
        type: '',
        groupName: '',
        // 是否临时执行记录
        isTempRecord: this.isTempRecord
      };

      return {
        visible: false,
        formData,
        addForm: JSON.parse(JSON.stringify(formData)),
        uerList: [], // 审核人列表
        executorList: [], // 业务人员列表

        // 表单验证规则
        addFormRules: {
          name: [
            { required: true, message: '请输入计划配置名称', trigger: 'blur' }
          ],
          autoOrder: [
            { required: true, message: '请选择是否自动派单', trigger: 'change' }
          ],
          ruleId: [
            { required: true, message: '请选择规则名称', trigger: 'change' }
          ],
          duration: [
            { required: true, message: '请输入计划完成时长', trigger: 'blur' }
          ],
          categoryLevelId: [
            { required: true, message: '请选择设备分类', trigger: 'change' }
          ],
          categoryId: [
            { required: true, message: '请选择设备类别', trigger: 'change' }
          ],
          groupId: [
            { required: true, message: '请选择巡点检部门', trigger: 'change' }
          ],
          executorId: [
            { required: true, message: '请选择巡点检人员', trigger: 'change' }
          ],
          urgent: [
            { required: true, message: '请选择紧急程度', trigger: 'change' }
          ]
        },

        statusList: [
          { label: '草稿', value: -1 },
          { label: '失效', value: 0 },
          { label: '生效', value: 1 }
        ],

        // 规则信息
        ruleInfo: null,
        // 设备信息
        deviceList: [],
        // 事项信息
        productionInfo: null,
        // 工艺路线
        workOrderInfo: null,
        // 加载状态
        loading: false,
        // 提交状态
        butLoading: false,
        produceTaskInfo: null
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },
      title() {
        if (this.ruleInfo) {
          return `新增${this.ruleInfo.name}计划`;
        }
        return '';
      }
    },
    watch: {
      visible(val) {
        if (val) {
          // 获取审核人列表数据
          this.getUserList();
        }
      }
    },
    methods: {
      // 关闭重置数据
      beforeClose() {
        this.$refs.addFormRef.resetFields();
        this.addForm = JSON.parse(JSON.stringify(this.formData));
        this.ruleInfo = null;
        this.deviceList = [];
        this.visible = false;
      },
      // 初始化 事项、工单、工序信息
      async init(row, workOrderInfo) {
        console.log('productionInfo', workOrderInfo);
        console.log('workOrderInfo', row, workOrderInfo);
        this.productionInfo = row;
        this.workOrderInfo = workOrderInfo;
        this.visible = true;

        if (this.productionInfo && this.productionInfo.eamPlanId) {
          // 执行中 已执行 获取基本信息
          this.getInfo();
        } else {
          // 获取设备信息 规则列表
          this.getRuleInfoAndList(row);
          this.getDeviceId(row.deviceId);
        }
      },
      // 已执行获取基本信息
      async getInfo() {
        try {
          this.loading = true;
          const { data } = await getById(this.productionInfo.eamPlanId);
          console.log('data 基本信息', data);
          // 数据回显
          this.$util.assignObject(this.addForm, data);
          // 类型转换
          this.addForm.urgent = this.addForm.urgent + '';
          this.addForm.executorId = data.executorId.split(',');
          // 赋值id
          this.addForm.id = this.productionInfo.id;
          this.addForm.isTempRecord = data.isTempRecord;

          // 获取部门用户列表
          this.getUserList({ groupId: data.groupId });
          this.ruleInfo = data.ruleInfo;
          this.ruleInfo.ruleItems = data.planDeviceList[0]?.workItems || [];
          this.deviceList = data.planDeviceList.map((item) => {
            return {
              name: item.substance.name,
              position: item.substance.position,
              id: item.substance.id,
              fixCode: item.substance.fixCode,
              codeNumber: item.substance.codeNumber
            };
          });
          this.loading = false;
        } catch (error) {
          this.loading = false;
        }
      },
      // 获取规则信息 和 规则事项列表
      async getRuleInfoAndList(row) {
        // 事项规则
        const data = await getDetail(row.ruleId);
        console.log('事项规则', data);
        this.ruleInfo = data;
        this.addForm.ruleId = data.id;
        this.addForm.ruleName = data.name;
        this.addForm.type = data.ruleType;
        // code 生成
        this.getOrderCode(data.ruleType);
      },
      // 查询设备信息
      async getDeviceId(id) {
        const data = await getAssetInfo(id);
        this.deviceList = [data];
        console.log('data -- 设备信息', data);
        this.addForm.categoryId = data.categoryId;
      },

      //选择部门(搜索)
      searchDeptNodeClick(info, data) {
        if (info) {
          // 根据部门获取人员
          this.addForm.groupName = data.name;
          const params = { groupId: info };
          this.getUserList(params);
        } else {
          this.addForm.groupId = null;
        }
      },
      // 过滤计划完成时长
      formDataDurationTime(value) {
        if (value > 0) {
          this.addForm.duration = value.replace(/^[0]+/, '');
        } else {
          this.addForm.duration = 0;
        }
      },
      // 获取审核人列表、巡点检人员
      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) {}
      },
      autoOrderChange(val) {
        if (val == 0) {
          this.addForm.executorId = '';
          this.addForm.groupId = '';
        }
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },
      // 添加事项规则
      addPostscript() {
        this.ruleInfo.ruleItems.push({
          sort: null,
          name: '',
          content: '',
          norm: '',
          isNew: true,
          operationGuide: {
            procedureList: [],
            toolList: []
          }
        });
      },
      /* 打开操作手册编辑款 */
      openOperationGuideDialogDialog(row, index) {
        this.$refs.operationGuideDialog.open(row, index);
      },
      // 删除事项规则
      deleteItem(index) {
        if (this.ruleInfo.ruleItems.length > 1) {
          this.ruleInfo.ruleItems.splice(index, 1);
        } else {
          this.$message.error('至少要有一个规则事项！');
        }
      },
      // 保存操作指导数据
      saveEdit(data, index) {
        this.$set(this.ruleInfo.ruleItems[index], 'operationGuide', data);
      },
      // code生成
      async getOrderCode(type) {
        if (type == 1) {
          const data = await getCode('patrolconfig_code');
          this.addForm.code = data;
        }
        if (type == 2) {
          const data = await getCode('maintainconfig_code');
          this.addForm.code = data;
        }
        if (type == 5) {
          const data = await getCode('quantity_code');
          this.addForm.code = data;
        }
      },
      // 提交
      submit() {
        // 验证表单
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) {
            return;
          }

          // 处理数据
          console.log('this.addForm', this.addForm);

          try {
            this.butLoading = true;
            let deviceInfo = this.deviceList[0] || {};

            // 请求参数
            const body = {
              id: this.addForm.id,
              planList: [
                {
                  ...this.addForm,
                  id: this.productionInfo.eamPlanId,
                  planId: this.productionInfo.eamPlanId,
                  executorId: this.addForm.executorId.join(','),
                  planDeviceList: [
                    {
                      deviceId: deviceInfo.id,
                      codeNumber: deviceInfo.codeNumber,
                      workItems: this.ruleInfo.ruleItems
                    }
                  ]
                }
              ],
              produceRoutingId: this.workOrderInfo.produceRoutingId,
              produceRoutingName: this.workOrderInfo.produceRoutingName,
              produceTaskConfigId: this.productionInfo.produceTaskConfigId,
              produceTaskId: this.productionInfo.produceTaskId,
              produceTaskName: this.productionInfo.produceTaskName,
              reportWorkType: this.productionInfo.reportWorkType,
              ruleId: this.ruleInfo.id,
              ruleName: this.ruleInfo.name,
              workOrderCode: this.workOrderInfo.code,
              workOrderId: this.workOrderInfo.id,
              batchNo: this.workOrderInfo.batchNo,
              executeMethod: this.productionInfo.executeMethod,
              formingNum: this.workOrderInfo.formingNum,
              productCode: this.workOrderInfo.productCode,
              productModel: this.workOrderInfo.productModel,
              productName: this.workOrderInfo.productName,
              specification: this.workOrderInfo.specification,
              isTempRecord: this.addForm.isTempRecord,
              itemType: this.productionInfo.itemType,
              deviceId: deviceInfo.id,
              deviceName: deviceInfo.name
            };

            console.log('body', body);

            // 批记录打开的统一这个接口，不区分是否临时记录
            if (this.isTempRecord) {
              await tempSaveOrUpdateAndSubmit(body);
            } else {
              await saveRuleRecord(body);
            }

            this.$message.success('派单成功！');
            this.butLoading = false;
            this.beforeClose();
            this.$emit('reload');
          } catch (error) {
            this.$message.error('派单失败！');
            this.butLoading = false;
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  ::v-deep .el-row {
    display: flex;
    flex-wrap: wrap;
  }

  ::v-deep .el-tab_box {
    display: flex;
    margin-top: 10px;
    height: 300px;
    width: 100%;

    .equipmentList_box {
      flex: 1;
      height: 100%;
      margin-right: 10px;
      display: flex;
      flex-direction: column;

      .divider {
        flex: 0 0 50px;

        .title {
          height: 35px;
        }
      }

      .el-table {
        overflow: auto;
      }
    }

    .ruleMatters_box {
      flex: 3;
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .divider {
        flex: 0 0 50px;

        .title {
          height: 35px;
        }
      }

      .el-table {
        overflow: auto;

        .operationGuide_box {
          width: 100%;
          height: 50px;
          display: flex;
          overflow: hidden;
          cursor: pointer;

          .left_content {
            flex: 0 0 200px;
            padding: 10px;
            box-sizing: border-box;
            border: 1px solid #c0c4cc;
            border-radius: 10px;
            margin-right: 10px;
            overflow-y: auto;
          }

          .right_content {
            flex: 1;
            padding: 10px;
            box-sizing: border-box;
            border: 1px solid #c0c4cc;
            border-radius: 10px;
            overflow-y: auto;
          }
        }
      }

      .el-table::before {
        display: none;
      }
    }
  }
</style>
