<template>
  <el-form
    class="form-no-message"
    ref="formRef"
    :show-message="false"
    label-position="left"
    :model="{
      categoryMsg,
      ...workReport
    }"
  >
    <div class="message-box">
      <ul>
        <li> <span class="label">报工次数</span>{{ countMsg.reportNum }}</li>
        <li>
          <span class="label">累计合格品数量</span
          >{{ countMsg.standardTotalNum }}</li
        >
        <li>
          <span class="label">累计合格品重量</span
          >{{ countMsg.standardTotalWeight }}KG</li
        >
        <li>
          <span class="label">累计投料产品数量</span
          >{{ countMsg.feedProductWeight }}</li
        >
      </ul>
      <div class="right">
        <el-form-item
          label="执行人工号"
          prop="executorId"
          required
          label-width="100px"
          ><personSelectRemote
            v-model="workReport.executorId"
            placeholder="请输入"
            @selfChange="
              (val, item) => (workReport.executorJobNum = item.jobNumber)
            "
        /></el-form-item>
        <el-form-item
          label="执行日期"
          required
          prop="executeTime"
          label-width="100px"
          ><el-date-picker
            v-model="workReport.executeTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择"
            :disabled="formData.dateType == 2"
          ></el-date-picker
        ></el-form-item>
      </div>
    </div>
    <el-card>
      <el-descriptions title="报工信息" direction="vertical" :column="7" border>
        <el-descriptions-item label="">
          <span class="label-required after" slot="label">投料数量（PCS）</span>
          <el-form-item
            label=""
            label-width="0"
            required
            class="w100"
            prop="categoryMsg.number"
          >
            <el-input
              class="w100"
              v-model="categoryMsg.number"
              @input="
                (value) =>
                  (categoryMsg.number = value ? parseInt(value) : value)
              "
              clearable
            ></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="">
          <span class="label-required after" slot="label">投料重量（KG）</span>
          <el-form-item
            label=""
            label-width="0"
            class="w100"
            prop="categoryMsg.totalWeight"
            ><el-input
              readonly
              class="w100"
              :value="
                (categoryMsg.totalWeight =
                  categoryMsg.number === ''
                    ? ''
                    : multiply(
                        categoryMsg.number,
                        infoData.productUnitWeight || 1
                      ))
              "
              clearable
            ></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="舟皿编号/名称" :span="2"
          ><el-input
            :value="`${boatMsg.code}/${boatMsg.name}`"
            @click.native="getCategory('8', 'boatMsg')"
          ></el-input
        ></el-descriptions-item>
        <el-descriptions-item label="舟皿数量" :span="3"
          ><el-input
            placeholder="请输入"
            v-model="boatMsg.extraField.boatNum"
          ></el-input
        ></el-descriptions-item>
        <el-descriptions-item label="质检项" :span="2">
          <el-input
            v-model="workReport.qualityItem"
            placeholder="请输入"
          ></el-input>
        </el-descriptions-item>
        <el-descriptions-item label="质检标准" :span="3">
          <el-input
            v-model="workReport.qualityStandard"
            placeholder="请输入"
          ></el-input
        ></el-descriptions-item>
        <!-- <el-descriptions-item label="">
          <span class="label-required after" slot="label">合格品数量(PCS)</span>
          <el-form-item
            label=""
            required
            label-width="0"
            class="w100"
            prop="productInfo.standardNum"
            ><el-input
              class="w100"
              v-model="workReport.productInfo.standardNum"
              @input="
                (value) =>
                  (workReport.productInfo.standardNum = value
                    ? parseInt(value)
                    : value)
              "
              clearable
            ></el-input> </el-form-item
        ></el-descriptions-item>
        <el-descriptions-item label=""
          ><span class="label-required after" slot="label">合格品重量(KG)</span>
          <el-form-item
            label=""
            label-width="0"
            class="w100"
            prop="productInfo.standardWeight"
            ><el-input
              readonly
              class="w100"
              :value="
                (workReport.productInfo.standardWeight =
                  workReport.productInfo.standardNum === ''
                    ? ''
                    : multiply(
                        workReport.productInfo.standardNum,
                        infoData.productUnitWeight || 1
                      ))
              "
              clearable
            ></el-input> </el-form-item
        ></el-descriptions-item> -->
        <el-descriptions-item label="">
          <span class="label-required after" slot="label"
            >不合格品数量(PCS)</span
          >
          <el-form-item
            label=""
            required
            label-width="0"
            class="w100"
            prop="productInfo.noStandardNum"
          >
            <el-input
              class="w100"
              v-model="workReport.productInfo.noStandardNum"
              @input="
                (value) =>
                  (workReport.productInfo.noStandardNum = value
                    ? parseInt(value)
                    : value)
              "
              clearable
              ><el-button
                type="primary"
                slot="suffix"
                size="mini"
                @click="handleOpen(1)"
                >处置</el-button
              ></el-input
            >
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="不合格品重量(KG)"
          ><el-input
            class="w100"
            readonly
            :value="
              (workReport.productInfo.noStandardWeight =
                workReport.productInfo.noStandardNum === ''
                  ? ''
                  : multiply(
                      workReport.productInfo.noStandardNum,
                      infoData.productUnitWeight || 1
                    ))
            "
            clearable
          ></el-input
        ></el-descriptions-item>
        <!-- <el-descriptions-item label="副产品重量(KG)"
          ><el-input
            class="w100"
            v-model="workReport.productInfo.byProductWeight"
            @input="
              (value) =>
                (workReport.productInfo.byProductWeight = value
                  ? parseInt(value)
                  : value)
            "
            clearable
            ><el-button
              type="primary"
              style="margin-top: 4px"
              slot="suffix"
              size="mini"
              @click="handleOpen(2)"
              >处置</el-button
            ></el-input
          ></el-descriptions-item
        > -->
        <el-descriptions-item label="备注">
          <el-input v-model="workReport.remark"></el-input
        ></el-descriptions-item>
      </el-descriptions>

      <ele-pro-table
        :columns="columns"
        :datasource="carList"
        :need-page="false"
        class="mt-16"
      >
        <template v-slot:toolbar>
          <el-link type="primary" @click="addCar">添加周转车</el-link>
        </template>
        <template v-slot:action="{ $index }">
          <el-link type="danger" @click="handleDelete($index)">删除</el-link>
        </template>
        <template v-slot:standardNum="{ row }">
          <el-input
            v-model="row.standardNum"
            @change="
              () => {
                row.standardWeight =
                  row.standardNum === ''
                    ? ''
                    : multiply(
                        row.standardNum,
                        infoData.productUnitWeight || 1
                      );
              }
            "
            placeholder="请输入"
          ></el-input>
        </template>
      </ele-pro-table>
      <el-descriptions
        title="设备信息"
        class="mt-16"
        direction="vertical"
        :column="7"
        border
      >
        <el-descriptions-item label="设备编码">{{
          workReportDeviceList.code
        }}</el-descriptions-item>
        <el-descriptions-item label="设备名称">{{
          workReportDeviceList.name
        }}</el-descriptions-item>
        <el-descriptions-item label="规格">{{
          workReportDeviceList.specification
        }}</el-descriptions-item>
        <el-descriptions-item label="型号">{{
          workReportDeviceList.model
        }}</el-descriptions-item>
        <el-descriptions-item label="升温曲线">
          <el-input
            placeholder="请输入"
            v-model="workReportDeviceList.extraField.temperatureRamp"
          ></el-input>
        </el-descriptions-item>

        <el-descriptions-item label="设备位置">{{
          workReportDeviceList.path
        }}</el-descriptions-item>
        <el-descriptions-item label="操作"
          ><el-link @click="getEquip" type="primary"
            >选择设备</el-link
          ></el-descriptions-item
        >
      </el-descriptions>
    </el-card>
    <equipmentDailog ref="equipmentRef" :taskId="taskInfo.id" />
    <catogaryDialog ref="catogaryDialogRef" />
    <carDialog ref="carDialogRef" />
    <handleDialog ref="handleDialogRef" />
  </el-form>
</template>

<script>
  import personSelectRemote from '@/components/CommomSelect/person-select-remote';
  import equipmentDailog from '@/components/EquipmentDailog/report-equipment';
  import { reportCount } from '@/api/produceOrder';
  import catogaryDialog from '../catogaryDialog.vue';
  import handleDialog from './components/handleDialog';
  import dayjs from 'dayjs';
  import { multiply } from '@/utils/math';
  import carDialog from '../carDialog.vue';
  export default {
    components: {
      handleDialog,
      personSelectRemote,
      equipmentDailog,
      carDialog,
      catogaryDialog
    },
    props: {
      infoData: {
        type: Object,
        default: () => ({})
      },
      taskInfo: {
        type: Object,
        default: () => ({})
      },
      formData: {
        type: Object,
        default: () => ({})
      },
      firstInfo: {
        type: Object,
        default: () => ({})
      },
      currentInfo: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        columns: [
          {
            label: '序号',
            type: 'index',
            width: 55
          },
          {
            label: '编码',
            prop: 'code'
          },
          {
            label: '名称',
            prop: 'name'
          },
          {
            label: '合格品数量',
            slot: 'standardNum'
          },
          {
            label: '合格品重量',
            prop: 'standardWeight'
          },
          {
            label: '操作',
            slot: 'action'
          }
        ],
        categoryMsg: {
          batchNo: '',
          number: '',
          totalWeight: '',
          brandNum: '',
          sourceCategoryId: '',
          rootCategoryLevelId: '9',
          name: '',
          code: ''
        },
        carList: [],
        disposeOrderList: [],
        workReport: {
          qualityItem: '',
          qualityStandard: '',
          executorId: '',
          executorJobNum: '',
          executeTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          remark: '',
          productInfo: {
            // byProductWeight: '',
            standardNum: '',
            standardWeight: '',
            noStandardNum: '',
            noStandardWeight: ''
          }
        },
        workReportDeviceList: {
          code: '',
          name: '',
          path: '',
          model: '',
          rootCategoryLevelId: '',
          specification: '',
          extraField: {
            temperatureRamp: ''
          }
        },
        countMsg: {},
        // 舟皿信息
        boatMsg: {
          code: '',
          name: '',
          path: '',
          model: '',
          rootCategoryLevelId: '',
          specification: '',
          extraField: {
            boatNum: ''
          }
        }
      };
    },
    watch: {
      taskInfo: {
        immediate: true,
        handler() {
          if (this.taskInfo.code) {
            this.getReportCount();
          }
        }
      },
      infoData: {
        immediate: true,
        handler() {
          if (
            this.infoData.id &&
            this.currentInfo.code == this.firstInfo.code &&
            this.infoData.deviceCode
          ) {
            // 设备
            this.workReportDeviceList = Object.assign(
              {},
              this.workReportDeviceList,
              {
                code: this.infoData.deviceCode,
                name: this.infoData.deviceName,
                rootCategoryLevelId: this.infoData.rootCategoryLevelId,
                path: this.infoData.path[0]?.pathName,
                model: this.infoData.model,
                sourceInstanceId: this.infoData.sourceInstanceId,
                specification: this.infoData.specification
              }
            );
          }
        }
      },
      formData: {
        immediate: true,
        handler() {
          if (this.formData.dateType == 2) {
            this.$set(
              this.workReport,
              'executeTime',
              this.formData.appointTime
            );
          }
        }
      }
    },
    created() {
      this.workReport.executorId = this.$store.state.user.info?.userId;
      this.workReport.executorJobNum = this.$store.state.user.info?.jobNumber;
    },
    methods: {
      multiply,
      handleDelete(index) {
        this.$confirm('确认删除当前周转车？').then(() => {
          this.carList.splice(index, 1);
        });
      },
      addCar() {
        this.$refs.carDialogRef.open(this.carList, (list) => {
          this.carList = list.map((item) => ({
            ...item,
            sourceCategoryId: item.categoryId,
            brandNum: item.brand,
            standardWeight: '',
            standardNum: ''
          }));
        });
      },
      handleOpen(disposeType) {
        this.$refs.handleDialogRef.open(disposeType, (data) => {
          data.workOrderCode = this.infoData.code;
          data.workOrderId = this.infoData.id;

          let index = this.disposeOrderList.find(
            (i) => i.disposeType == disposeType
          );
          if (index > -1) {
            this.disposeOrderList[index] = data;
          } else {
            this.disposeOrderList.push(data);
          }
        });
      },
      getCategory(id, memo) {
        this.$refs.catogaryDialogRef.open(id, this[memo], (res) => {
          this[memo].rootCategoryLevelId = res.categoryLevelId;
          this[memo].code = res.code;
          this[memo].name = res.name;
          this[memo].specification = res.specification;
          this[memo].sourceInstanceId = res.id;
          if (memo === 'moduleMsg') {
            this[memo].model = res.modelType;
            this[memo].extraField.stampingTimes = '';
          } else {
            this[memo].extraField.num = '';
          }
        });
      },
      async getReportCount() {
        const res = await reportCount({
          taskCode: this.taskInfo.code,
          workOrderId: this.infoData.id
        });

        this.countMsg = res;
      },
      getEquip() {
        this.$refs.equipmentRef.openSingle(
          [this.workReportDeviceList],
          (res) => {
            this.workReportDeviceList.code = res.code;
            this.workReportDeviceList.name = res.name;

            this.workReportDeviceList.model = res.category?.category?.modelType;
            this.workReportDeviceList.specification =
              res.category?.category?.specification;
            this.workReportDeviceList.sourceInstanceId = res.id;
            this.workReportDeviceList.rootCategoryLevelId =
              res.rootCategoryLevelId;
            this.workReportDeviceList.path = res.positionList[0]?.pathName;
          }
        );
      },
      report(fun) {
        this.$refs.formRef.validate((value) => {
          if (value) {
            if (!this.workReportDeviceList.code) {
              return this.$message.error('请选择设备');
            }
            if (!this.carList.length) {
              return this.$message.error('请选择周转车');
            }

            this.$confirm('是否确定要报工?', '提示').then(() => {
              this.categoryMsg = Object.assign(this.categoryMsg, {
                brandNum: this.infoData.brandNo,
                sourceCategoryId: this.infoData.categoryId,
                name: this.infoData.productName,
                code: this.infoData.productCode
              });

              const workReportDeviceList = this.carList;
              if (this.workReportDeviceList.code) {
                workReportDeviceList.push(this.workReportDeviceList);
              }

              if (this.boatMsg.code) {
                workReportDeviceList.push(this.boatMsg);
              }
              fun({
                checkState: 1,
                disposeOrderList: this.disposeOrderList,
                workReport: this.workReport,
                workReportDeviceList,
                workReportCategoryList: [this.categoryMsg]
              }).then((res) => {
                // this.$message.success('报工成功！');
                // this.getReportCount();
              });
            });
          } else {
            this.$message.error('请输入必填项！');
          }
        });
      }
    }
  };
</script>

<style lang="scss" scoped>
  .form-no-message {
    :deep(.el-input-number) {
      .el-input__inner {
        text-align: left !important;
      }
    }
  }
  .message-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    .label {
      margin-right: 5px;
    }
    ul {
      list-style: none;
      display: flex;
      align-items: center;
      justify-content: flex-start;

      li {
        margin-right: 20px;
      }
    }

    .right {
      padding-top: 22px;
      display: flex;
      align-items: center;

      .el-form-item {
        margin-left: 10px;
      }
    }
  }
</style>
