<template>
  <el-dialog
    title="报工"
    :visible.sync="dialogVisible"
    width="60%"
    :before-close="handleClose"
  >
    <div>
      <!-- <el-button type="primary" plain round @click="openMaintenancePlan">
        设备保养计划
      </el-button> -->
      <div
        v-if="loading || ruleRecordsList.length > 0"
        class="step-list"
        v-loading="loading"
      >
        <ele-pro-table
          ref="table"
          row-key="id"
          :columns="columns"
          :datasource="ruleRecordsList"
          cache-key="mes-ruleRecordsList-2511172018"
          autoAmendPage
          :need-page="false"
          @refresh="getData"
        >
          <template v-slot:num="{ $index }">
            <div class="circle">{{ $index + 1 }}</div>
          </template>

          <template v-slot:action="{ row }">
            <el-button
              :type="row.executeStatus == 0 ? 'primary' : 'default'"
              class="status-btn"
              @click="openMaintenancePlan(row)"
            >
              {{ executeStatusTest(row.executeStatus) }}
            </el-button>
          </template>
        </ele-pro-table>
      </div>
      <el-empty v-else></el-empty>
    </div>
    <template #footer>
      <el-button @click="handleUpdate" type="primary" :loading="butLoad"
        >更新</el-button
      >
      <el-button @click="handleConfirm" type="primary">确定</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>

    <releaseRulesDialog ref="releaseRulesDialogRef" @reload="getData" />

    <taskDialog ref="taskDialogRef" @reload="getData" />

    <!-- 派单 -->
    <programRulesDialog
      ref="programRulesDialogRef"
      @reload="getData"
    ></programRulesDialog>

    <!-- 报工 -->
    <workOrderReport
      ref="workOrderReportRef"
      @refresh="getData"
    ></workOrderReport>

    <PlanRulesDialog
      ref="planRulesDialogRef"
      @reload="getData"
    ></PlanRulesDialog>
  </el-dialog>
</template>

<script>
  import releaseRulesDialog from './releaseRulesDialog.vue';
  import {
    getLastRuleRecords,
    getProduceTaskInstanceId
  } from '@/api/producetaskrulerecord/index.js';
  import taskDialog from './taskDialog.vue';
  import PlanRulesDialog from './PlanRulesDialog.vue';
  import dictMixins from '@/mixins/dictMixins';
  import tableColumnsMixin from '@/mixins/tableColumnsMixin';
  import programRulesDialog from '@/views/batchRecord/components/programRulesDialog.vue';
  import workOrderReport from '@/views/batchRecord/components/workOrderReport.vue';

  export default {
    mixins: [dictMixins, tableColumnsMixin],
    components: {
      releaseRulesDialog,
      taskDialog,
      PlanRulesDialog,
      programRulesDialog,
      workOrderReport
    },
    data() {
      return {
        dialogVisible: false,
        ruleRecordsList: [],
        // 工艺路线
        workOrderInfo: null,
        // 工序信息
        produceTaskInfo: null,
        // 	报工类型，参考字典项：record_rules_report_work_type，1-产前准备，2-过程控制，3-产后检查
        reportWorkType: 1,
        butLoad: false,
        // 记录规则
        showReleaseRulesDialog: false,
        loading: true,
        programRulesDialogVisible: false,
        programRulesInfo: {}
      };
    },
    computed: {
      columns() {
        return [
          {
            width: 50,
            type: 'index',
            slot: 'num',
            align: 'center',
            label: '序号'
          },
          {
            prop: 'produceTaskName',
            label: '名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150,
            formatter: (row) => {
              return row.ruleName || row.itemTaskName || row.planConfigName;
            }
          },
          {
            prop: 'executeMethod',
            label: '执行方式',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150,
            formatter: (row) => {
              return this.getDictValue('记录规则执行方式', row.executeMethod);
            }
          },
          {
            prop: 'reportUserName',
            label: '报工人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'finishTime',
            label: '报工时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'duration',
            label: '工时',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150,
            formatter: (row) => {
              // 毫秒转小时
              return row.duration && row.executeStatus == 2
                ? (row.duration / 1000 / 60 / 60).toFixed(2) + ' 时'
                : '';
            }
          },
          // 操作
          {
            label: '操作',
            align: 'center',
            width: 130,
            fixed: 'right',
            slot: 'action'
          }
        ];
      }
    },
    methods: {
      open(workOrderInfo, produceTaskInfo, reportWorkType) {
        console.log('workOrderInfo 工单信息', workOrderInfo);
        console.log('工序信息', produceTaskInfo);
        this.workOrderInfo = workOrderInfo;
        this.produceTaskInfo = produceTaskInfo;
        this.reportWorkType = reportWorkType;

        this.dialogVisible = true;
        this.getData(workOrderInfo.id, produceTaskInfo.id);
      },
      executeStatusTest(status) {
        switch (status) {
          case 0:
            return '未报工';
          case 1:
            return '执行中';
          default:
            return '已报工';
        }
      },
      // 获取数据
      async getData() {
        if (!this.workOrderInfo || !this.produceTaskInfo) return;
        this.loading = true;
        const body = {
          workOrderId: this.workOrderInfo.id,
          produceTaskId: this.produceTaskInfo.id,
          reportWorkType: this.reportWorkType,
          isTempRecord: 0
        };
        const data = await getLastRuleRecords(body);
        const produceTaskInstanceInfo = await getProduceTaskInstanceId(
          this.workOrderInfo.id,
          this.produceTaskInfo.id
        );
        this.ruleRecordsList = data.map((i) => {
          // 工序名称
          i.produceTaskName = produceTaskInstanceInfo.name;
          i.produceTaskInstanceId = produceTaskInstanceInfo.id;
          return i;
        });
        console.log('list', produceTaskInstanceInfo);
        console.log('报工流程 事项', this.ruleRecordsList);
        this.loading = false;
      },
      handleClose() {
        this.dialogVisible = false;
        this.workOrderInfo = null;
        this.produceTaskInfo = null;
        this.$emit('close');
      },
      async handleUpdate() {
        try {
          this.butLoad = true;
          await this.getData();
          // 更新逻辑
          this.$message.success('已更新');
          this.butLoad = false;
        } catch (error) {
          this.butLoad = false;
        }
      },
      handleConfirm() {
        // 确定逻辑
        this.dialogVisible = false;
      },
      openMaintenancePlan(item) {
        console.log('item~~~', item);
        // itemType 事项类型
        if (item.itemType == 1) {
          if((!item.planOrders || item.planOrders.length == 0) && item.executeMethod == 1) {
            this.$message.error('未生成设备计划');
            return;
          }
          // 计划规则 巡点检 设备保养
          this.$refs.planRulesDialogRef.open(item);
        } else if (item.itemType == 2) {
          // 事件驱动
          if(item.executeMethod == 1) {
            // 是否有计划
            if(!item.plans || item.plans.length == 0) {
              this.$message.error('未生成记录计划');
              return;
            }
            // 有计划无工单  派单
            if(item.plans && item.plans.length > 0 && (!item.records || item.records.length == 0)) {
              this.$refs.programRulesDialogRef.open('dispatch', item.plans[0], item.plans);
              return;
            }
            // 有计划有工单未报工执行中  报工
            if(item.plans && item.plans.length > 0 && item.records && item.records.length > 0 && (item.executeStatus == 1 || item.executeStatus == 0)) {
              item.plans.forEach(plan => {
                // 找到records数组中planid与当前plan.id匹配的记录
                plan.matchedRecords = item.records.filter(record => record.planId == plan.id);
              });
              console.log('匹配后的plans数组:', item);
              this.$refs.workOrderReportRef.open('add', item.plans[0]?.matchedRecords[0], item.plans[0]?.matchedRecords);
              return;
            }
            // 有计划有工单已报工  详情
            if(item.plans && item.plans.length > 0 && item.records && item.records.length > 0 && item.executeStatus == 2) {
              item.plans.forEach(plan => {
                // 找到records数组中planid与当前plan.id匹配的记录
                plan.matchedRecords = item.records.filter(record => record.planId == plan.id);
              });
              console.log('详情匹配后的plans数组:', item);
              if(item.plans[0]?.matchedRecords.length == 0) {
                this.$message.error('未生成工单');
                return
              }
              this.$refs.workOrderReportRef.open('detail', item.plans[0]?.matchedRecords[0], item.plans[0]?.matchedRecords);
              return;
            }
          }
          this.$refs.releaseRulesDialogRef.open(
            item,
            this.workOrderInfo,
            this.produceTaskInfo
          );
        } else {
          // 任务确认
          this.$refs.taskDialogRef.open(
            item,
            this.workOrderInfo,
            this.produceTaskInfo
          );
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .step-list {
    display: flex;
    flex-direction: column;
    gap: 24px;
    // padding: 24px;

    .circle {
      width: 28px;
      height: 28px;
      background: #6cb300;
      color: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      font-weight: bold;
      flex-shrink: 0;
    }

    .desc {
      flex: 1;
      font-size: 14px;
      color: #333;
      max-width: 300px;
      white-space: pre-line;
      word-break: break-all;
    }

    .methods {
      max-width: 90px;
      white-space: pre-line;
      word-break: break-all;
    }

    .status-btn {
      width: 100px;
      height: 40px;
      font-size: 16px;
      margin: 5px 0;

      &.el-button--default {
        background: #e1e1e1;
        color: #999;
        border: none;
      }
      &.el-button--primary {
        background: #17a2f8;
        color: #fff;
        border: none;
      }
    }
  }

  .step-item {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    gap: 32px;
    justify-content: space-around;
  }
</style>
