<template>
  <ele-modal
    :centered="true"
    :close-on-click-modal="false"
    :maxable="true"
    :visible.sync="visible"
    append-to-body
    custom-class="ele-dialog-form long-dialog-form"
    title="任务列表"
    width="85%"
    @close="handleClose"
  >
    <ele-pro-table
      ref="fileTable"
      :columns="columns"
      :datasource="workList"
      :loading="loading"
      style="min-height: 400px"
    >
      <template v-slot:realStartTime="{ row }">
        <el-date-picker
          v-model="row.realStartTime"
          :picker-options="{
            disabledDate: (time) => {
              return (
                row.realEndTime && time.getTime() > new Date(row.realEndTime)
              );
            }
          }"
          placeholder="选择实际开始时间"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </template>
      <template v-slot:realEndTime="{ row }">
        <el-date-picker
          v-model="row.realEndTime"
          :picker-options="{
            disabledDate: (time) => {
              return (
                row.realStartTime &&
                time.getTime() < new Date(row.realStartTime)
              );
            }
          }"
          placeholder="选择结束日期"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </template>
      <template v-slot:qualifiedQuantity="{ row }">
        <el-input
          v-model="row.qualifiedQuantity"
          placeholder="请输入"
          type="number"
          @input="(e) => handleQuantityInput(e, 'qualifiedQuantity', row)"
        ></el-input>
      </template>
      <template v-slot:qualifiedWeight="{ row }">
        <el-input
          v-model="row.qualifiedWeight"
          placeholder="请输入"
          type="number"
          @input="(e) => handleWeightInput(e, 'qualifiedWeight', row)"
        ></el-input>
      </template>
      <template v-slot:unqualifiedQuantity="{ row }">
        <el-input
          v-model="row.unqualifiedQuantity"
          placeholder="请输入"
          type="number"
          @input="(e) => handleQuantityInput(e, 'unqualifiedQuantity', row)"
        ></el-input>
      </template>
      <template v-slot:unqualifiedWeight="{ row }">
        <el-input
          v-model="row.unqualifiedWeight"
          placeholder="请输入"
          type="number"
          @input="(e) => handleWeightInput(e, 'unqualifiedWeight', row)"
        ></el-input>
      </template>
      <template v-slot:assigneeRemark="{ row }">
        <el-input
          v-model="row.assigneeRemark"
          placeholder="请输入"
          type="textarea"
        ></el-input>
      </template>
      <template v-slot:action="{ row }">
        <!-- <el-popconfirm title="确定完成这个任务？" @confirm="sureData(row)">
          <template v-slot:reference>
            <el-link :underline="false" type="primary">确定 </el-link>
          </template>
        </el-popconfirm> -->
        <el-popconfirm title="确认本次报工？" @confirm="saveData(row)">
          <template v-slot:reference>
            <el-link  :underline="false" type="primary">报工 </el-link>
          </template>
        </el-popconfirm>

        <el-link
          style="margin-left: 10px"
          :underline="false"
          type="primary"
          @click="viewRecords(row.id)"
          >报工修改记录</el-link
        >
      </template>
    </ele-pro-table>
    <modifyDialog ref="modifyRef" />
  </ele-modal>
</template>

<script>
  import {
    batchUpdateRealTime,
    listUpdateRealTimeRecord,
    pageAssigneeByTask,
    batchUpdateRealTimeConfirm
  } from '@/api/workOrderList';
  import modifyDialog from '@/views/taskList/components/modifyDialog.vue';

  export default {
    // components: { WorkTimeHistory, Details },
    components: { modifyDialog },
    data() {
      return {
        visible: false,
        workList: [],
        columns: [
          {
            title: '序号',
            type: 'index',
            width: 60,
            align: 'center',
            fixed: 'left'
          },
          {
            label: '执行对象名称',
            prop: 'assigneeName',
            width: 180,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '执行类型',
            prop: 'assigneeType',
            width: 100,
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              if (!row.assigneeType) return '';
              return row.assigneeType.desc;
            }
          },
          {
            label: '任务开始时间',
            prop: 'startTime',
            width: 170,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '任务结束时间',
            prop: 'endTime',
            width: 170,
            align: 'center',
            showOverflowTooltip: true
          },

          {
            label: '任务数量',
            prop: 'quantity',
            width: 120,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '任务重量(kg)',
            prop: 'weight',
            width: 120,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'realStartTime',
            label: '实际开始时间',
            prop: 'realStartTime',
            width: 250,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'realEndTime',
            label: '实际结束时间',
            prop: 'realEndTime',
            width: 250,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            label: '工时',
            prop: 'durationText',
            width: 140,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'qualifiedQuantity',
            label: '合格数量',
            prop: 'qualifiedQuantity',
            width: 160,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'qualifiedWeight',
            label: '合格重量',
            prop: 'qualifiedWeight',
            width: 160,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'unqualifiedQuantity',
            label: '不合格数量',
            prop: 'unqualifiedQuantity',
            width: 160,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'unqualifiedWeight',
            label: '不合格重量',
            prop: 'unqualifiedWeight',
            width: 160,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            slot: 'assigneeRemark',
            label: '备注',
            prop: 'assigneeRemark',
            width: 230,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            slot: 'action',
            label: '操作',
            align: 'center',
            width: 165,
            resizable: false,
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        loading: false
      };
    },
    computed: {},
    methods: {
      open(queryParam, workData) {
        this.visible = true;
        this.params = {
          produceRoutingId: workData.produceRoutingId,
          taskId: this.$store.state.user.taskObj.id,
          mesWorkOrderId: workData.id,
          categoryId: workData.categoryId,
          apsWorkOrderId: workData.apsWorkOrderId
        };

        this.getData();
      },
      // 确定完成
      sureData(row) {
        let params = {
          // realStartTime: row.realStartTime,
          // realEndTime: row.realEndTime,
          qualifiedQuantity: row.qualifiedQuantity,
          qualifiedWeight: row.qualifiedWeight,
          unqualifiedQuantity: row.unqualifiedQuantity,
          unqualifiedWeight: row.unqualifiedWeight,
          remark: row.assigneeRemark,
          apsAssigneeId: row.id
        };
        batchUpdateRealTimeConfirm(params).then((res)=>{
          console.log(res,'res 1111')
        })
      },
      getData() {
        this.workList = [];
        this.loading = true;
        for (let key in this.params) {
          if (!this.params[key]) {
            return;
          }
        }
        pageAssigneeByTask(this.params)
          .then((res) => {
            this.loading = false;
            this.workList = res.list;
          })
          .catch((err) => {
            this.loading = false;
            this.workList = [];
            this.$message.error(err.message);
          });
      },
      //   保存
      saveData(row) {
        if (!row.realStartTime) {
          return this.$message.warning('请选择开始时间');
        }
        if (!row.realEndTime) {
          return this.$message.warning('请选择结束时间');
        }
        if (!row.qualifiedQuantity && row.qualifiedQuantity != 0) {
          return this.$message.warning('请输入合格数量');
        }
        if (!row.qualifiedWeight && row.qualifiedWeight != 0) {
          return this.$message.warning('请输入合格重量');
        }
        if (!row.unqualifiedQuantity && row.unqualifiedQuantity != 0) {
          return this.$message.warning('请输入不合格数量');
        }
        if (!row.unqualifiedWeight && row.unqualifiedWeight != 0) {
          return this.$message.warning('请输入不合格重量');
        }
        if (
          row.qualifiedQuantity - 0 + (row.unqualifiedQuantity - 0) !=
          row.quantity - 0
        ) {
          return this.$message.warning(
            `合格数量加不合格数量需要等于任务数量${row.quantity}`
          );
        }
        if (
          row.qualifiedWeight - 0 + (row.unqualifiedWeight - 0) !=
          row.weight - 0
        ) {
          return this.$message.warning(
            `合格重量加不合格重量需要等于任务重量${row.weight}`
          );
        }

        let params = {
          realStartTime: row.realStartTime,
          realEndTime: row.realEndTime,
          qualifiedQuantity: row.qualifiedQuantity,
          qualifiedWeight: row.qualifiedWeight,
          unqualifiedQuantity: row.unqualifiedQuantity,
          unqualifiedWeight: row.unqualifiedWeight,
          remark: row.assigneeRemark,
          apsAssigneeId: row.id
        };
        // getData
        batchUpdateRealTime([params])
          .then((res) => {
            if (res) {
              this.$message.success('操作成功');
              this.getData();
            }
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      },
      // 重量正则判断
      handleWeightInput(e, type, row) {
        // 过滤非数字和非小数点字符（包括负号）
        let value = e.replace(/[^\d.]/g, '');
        // 限制只能有一个小数点
        const dotCount = (value.match(/\./g) || []).length;
        if (dotCount > 1) {
          value = value.slice(0, value.lastIndexOf('.'));
        }
        // 限制不能以小数点开头
        if (value.startsWith('.')) {
          value = '0' + value;
        }
        // 更新绑定值
        row[type] = value;
        this.calculateWeight(row, type);
      },
      // 数量正则 quantity
      handleQuantityInput(e, type, row) {
        // 过滤非数字字符（包括负号）
        let value = e.replace(/[^\d]/g, '');
        // 限制不能以 0 开头（除非是 0 本身）
        if (value.startsWith('0') && value.length > 1) {
          value = value.slice(1);
        }
        // 更新绑定值
        row[type] = value;
        this.calculateQuantity(row, type);
      },
      //计算重量
      calculateWeight(row, type) {
        let total = row.qualifiedWeight - 0 + (row.unqualifiedWeight - 0);
        if (total > row.weight) {
          row[type] = 0;
          this.$message.warning('合格重量加不合格重量不能大于任务重量');
        }
      },
      // 计算数量
      calculateQuantity(row, type) {
        let total = row.qualifiedQuantity - 0 + (row.unqualifiedQuantity - 0);
        if (total > row.quantity) {
          row[type] = 0;
          this.$message.warning('合格数量加不合格数量不能大于任务数量');
        }
      },
      // 查看修改记录
      viewRecords(apsAssigneeId) {
        listUpdateRealTimeRecord(apsAssigneeId)
          .then((res) => {
            if (res && res.length > 0) {
              this.$refs.modifyRef.open(res);
            } else {
              this.$message.warning('暂无修改历史记录数据');
            }
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      },
      handleClose() {
        this.visible = false;
      },
      close() {
        this.detailsVisible = false;
      }
    }
  };
</script>
