<template>
  <ele-modal
    :before-close="cancel"
    :close-on-click-modal="false"
    :maxable="true"
    :title="title"
    :visible.sync="detailsVisible"
    append-to-body
    custom-class="ele-dialog-form"
    width="75vw"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="right"
      label-width="110px"
    >
      <el-row>
        <headerTitle style="margin-top: 15px" title="报工信息"></headerTitle>
        <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
          <el-form-item
            :rules="{
              required: true,
              message: '请选择实际开始时间',
              trigger: 'change'
            }"
            label="实际开始时间"
            prop="realStartTime"
          >
            <el-date-picker
              v-model="form.realStartTime"
              :disabled="inputDis"
              class="time_select"
              placeholder="选择实际开始时间"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="handleTimeChange"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
          <el-form-item
            :rules="{
              required: true,
              message: '请选择实际结束时间',
              trigger: 'change'
            }"
            label="实际结束时间"
            prop="realEndTime"
          >
            <el-date-picker
              v-model="form.realEndTime"
              :disabled="inputDis"
              class="time_select"
              placeholder="选择实际结束时间"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="handleTimeChange"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
          <el-form-item label="合格数量" prop="qualifiedQuantity">
            <el-input
              v-model.number="form.qualifiedQuantity"
              :disabled="inputDis"
              placeholder="请输入"
              type="number"
              @input="(e) => handleQuantityInput(e, 'qualifiedQuantity')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
          <el-form-item label="不合格数量" prop="unqualifiedQuantity">
            <el-input
              v-model.number="form.unqualifiedQuantity"
              :disabled="inputDis"
              placeholder="请输入"
              type="number"
              @input="(e) => handleQuantityInput(e, 'unqualifiedQuantity')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
          <el-form-item label="合格重量" prop="qualifiedWeight">
            <el-input
              v-model.number="form.qualifiedWeight"
              :disabled="inputDis"
              placeholder="请输入"
              type="number"
              @input="(e) => handleWeightInput(e, 'qualifiedWeight')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="12" :sm="12" :xl="12" :xs="12">
          <el-form-item label="不合格重量" prop="unqualifiedWeight">
            <el-input
              v-model.number="form.unqualifiedWeight"
              :disabled="inputDis"
              placeholder="请输入"
              type="number"
              @input="(e) => handleWeightInput(e, 'unqualifiedWeight')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注信息">
            <el-input
              v-model="form.remark"
              :disabled="inputDis"
              :rows="2"
              placeholder="请输入"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="tool_btn">
        <el-button
          type="primary"
          size="medium"
          @click="submitAdd"
          :loading="loadingBtn"
          >报工</el-button
        >
      </el-row>
      <headerTitle style="margin-top: 15px" title="工单信息"></headerTitle>
      <el-row :gutter="10" class="basic">
        <el-col
          v-for="item in fieldMap.orderList"
          :key="item.prop"
          :lg="8"
          :md="12"
          :sm="12"
          :xl="8"
          :xs="12"
        >
          <el-form-item :label="item.label" class="form80">
            <el-input v-model="current[item.prop]" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <headerTitle style="margin-top: 15px" title="任务信息"></headerTitle>
      <el-row :gutter="10" class="basic">
        <el-col
          v-for="item in fieldMap.taskList"
          :key="item.prop"
          :lg="8"
          :md="12"
          :sm="12"
          :xl="8"
          :xs="12"
        >
          <el-form-item :label="item.label" class="form80">
            <el-input v-model="current[item.prop]" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="title === '详情'">
        <headerTitle style="margin-top: 15px" title="报工记录"></headerTitle>
        <ModifyRecord ref="ModifyRecordRef" :list="list" />
      </el-row>
      <div slot="footer" class="tool_btn">
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-form>
  </ele-modal>
</template>

<script>
  import {
    listWorkCenter,
    batchUpdateRealTime,
    listUpdateRealTimeRecord
  } from '@/api/workOrderList';
  import ModifyRecord from '@/views/taskList/components/ModifyRecord.vue';
  export default {
    components: {
      ModifyRecord
    },
    props: {
      currentRow: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        title: '详情',
        form: {
          realEndTime: '',
          realStartTime: '',
          unqualifiedWeight: '',
          unqualifiedQuantity: '',
          qualifiedWeight: '',
          qualifiedQuantity: '',
          remark: ''
        },
        rules: {
          qualifiedQuantity: [
            {
              required: true,
              message: '请输入合格数量',
              trigger: 'blur'
            }
          ],
          qualifiedWeight: [
            {
              required: true,
              message: '请输入合格重量',
              trigger: 'blur'
            }
          ],
          unqualifiedQuantity: [
            {
              required: true,
              message: '请输入不合格数量',
              trigger: 'blur'
            }
          ],
          unqualifiedWeight: [
            {
              required: true,
              message: '请输入不合格重量',
              trigger: 'blur'
            }
          ]
        },
        current: {},
        detailsVisible: false,
        fieldMap: {
          orderList: [
            { label: '生产订单编码:', prop: 'workOrderCode' },
            { label: '计划编号:', prop: 'productionPlanCode' },
            { label: '工艺路线:', prop: 'produceRoutingName' },
            { label: '要求生产数量:', prop: 'quantity' },
            { label: '要求生产重量:', prop: 'weight' },
            { label: '所属工厂:', prop: 'factoryName' },
            { label: '所属班组:', prop: 'assignTeamName' },
            { label: '计划开始时间:', prop: 'planStartTime' },
            { label: '计划结束时间:', prop: 'planCompleteTime' }
          ],
          taskList: [
            { label: '任务编码:', prop: 'assignCode' },
            { label: '工序名称:', prop: 'taskName' },
            { label: '执行类型:', prop: 'assigneeType' },
            { label: '执行对象名称:', prop: 'assigneeName' },
            { label: '工时:', prop: 'durationText' },
            { label: '任务开始时间:', prop: 'startTime' },
            { label: '任务结束时间:', prop: 'endTime' },
            { label: '任务数量:', prop: 'quantity' },
            { label: '任务重量(kg):', prop: 'weight' }
          ]
        },
        loadingBtn: false,
        list: []
      };
    },
    computed: {
      inputDis() {
        return this.title === '详情';
      }
    },
    methods: {
      open(type, row, form) {
        this.title = type === 'report' ? '报工' : '详情';
        this.detailsVisible = true;
        this.current = { ...row };
        if (form.realEndTime) {
          this.$nextTick(() => {
            this.form = { ...form };
          });
          if (type !== 'report') {
            listUpdateRealTimeRecord(row.apsAssigneeId)
              .then((res) => {
                if (res) {
                  this.list = res;
                }
              })
              .catch((err) => {
                this.$message.error(err.message);
              });
          }
        }
        this.getData();
      },
      cancel() {
        this.form = {
          realEndTime: '',
          realStartTime: '',
          unqualifiedWeight: '',
          unqualifiedQuantity: '',
          qualifiedWeight: '',
          qualifiedQuantity: '',
          remark: ''
        };
        this.$refs.form.resetFields();
        this.detailsVisible = false;
      },
      async getData() {
        try {
          const res = await listWorkCenter(this.current.firstTaskId);
          this.$set(this.current, 'factoryName', res[0].factoryName);
        } catch (err) {
          this.$message.warning(err.message);
        }
      },
      // 时间选择
      handleTimeChange() {
        // 如果结束时间早于开始时间，清空结束时间
        if (this.form.realStartTime && this.form.realEndTime) {
          const realStartTime = new Date(this.form.realStartTime).getTime();
          const realEndTime = new Date(this.form.realEndTime).getTime();
          if (realStartTime > realEndTime) {
            this.form.realEndTime = '';
            this.$message.warning('结束时间不能早于开始时间');
          }
        }
      },
      // 重量正则判断
      handleWeightInput(e, type) {
        // 过滤非数字和非小数点字符（包括负号）
        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;
        }
        // 更新绑定值
        this.form[type] = value;
        this.calculateWeight(type);
      },
      //计算重量
      calculateWeight(type) {
        let total =
          this.form.qualifiedWeight - 0 + (this.form.unqualifiedWeight - 0);
        if (total > this.current.weight) {
          this.form[type] = 0;
          this.$message.warning('合格重量加不合格重量不能大于任务重量');
        }
      },
      // 计算数量
      calculateQuantity(type) {
        let total =
          this.form.qualifiedQuantity - 0 + (this.form.unqualifiedQuantity - 0);
        if (total > this.current.quantity) {
          this.form[type] = 0;
          this.$message.warning('合格数量加不合格数量不能大于任务数量');
        }
      },
      // 数量正则 quantity
      handleQuantityInput(e, type) {
        // 过滤非数字字符（包括负号）
        let value = e.replace(/[^\d]/g, '');
        // 限制不能以 0 开头（除非是 0 本身）
        if (value.startsWith('0') && value.length > 1) {
          value = value.slice(1);
        }
        // 更新绑定值
        this.form[type] = value;
        this.calculateQuantity(type);
      },
      submitAdd() {
        this.$refs.form.validate((valid) => {
          if (!valid) return;
          if (
            this.form.qualifiedQuantity -
              0 +
              (this.form.unqualifiedQuantity - 0) !==
            this.current.quantity
          ) {
            return this.$message.warning(
              `合格数量加不合格数量要等于任务数量${this.current.quantity}`
            );
          }
          if (
            this.form.qualifiedWeight -
              0 +
              (this.form.unqualifiedWeight - 0) !==
            this.current.weight
          ) {
            return this.$message.warning(`合格重量加不合格重量要等于任务重量${this.current.weight}`);
          }
          let data = {
            ...this.form,
            apsAssigneeId: this.current.apsAssigneeId
          };
          this.loadingBtn = true;
          batchUpdateRealTime([data])
            .then((res) => {
              this.loadingBtn = false;
              if (res) {
                this.$message.success('操作成功');
                this.cancel();
                this.$emit('success');
              }
            })
            .catch((err) => {
              this.loadingBtn = false;
              this.$message.error(err.message);
            });
        });
      }
    }
  };
</script>

<style scoped lang="scss">
  ::v-deep .time_select {
    width: 100%;
  }

  ::v-deep .tool_btn {
    text-align: right;

    .el-button {
      padding: 10px 18px !important;
      font-size: 15px !important;
    }
  }
</style>
