<template>
  <el-form
    class="form-no-message"
    :model="{ categoryMsg, ...workReport }"
    ref="formRef"
    :show-message="false"
  >
    <div class="message-box">
      <ul>
        <li> <span class="label">报工次数</span> {{ countMsg.reportNum }}</li>
        <li>
          <span class="label">累计合格品数量</span>
          {{ countMsg.standardTotalNum }}PCS</li
        >
        <li>
          <span class="label">累计合格品重量</span>
          {{ countMsg.standardTotalWeight }}KG</li
        >
        <li>
          <span class="label">累计投料重量</span>
          {{ countMsg.feedMaterielWeight }}KG</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="2">
          <span class="label-required after" slot="label">原料编码/名称</span>
          <el-form-item
            label=""
            required
            label-width="0"
            class="w100"
            prop="categoryMsg.code"
          >
            <el-input
              placeholder="请输入"
              :value="`${categoryMsg.code}/${categoryMsg.name}`"
              @click.native="getMaterial"
            ></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="原料牌号">{{
          categoryMsg.brandNum
        }}</el-descriptions-item>
        <el-descriptions-item label="库存地点">
          <span slot="label" class="label-required after">库存地点</span>
          <el-form-item
            label=""
            label-width="0"
            class="w100"
            prop="categoryMsg.position"
          >
            <DictSelection
              v-model="categoryMsg.position"
              dict-name="仓库"
              @itemChange="warehuseChange"
            ></DictSelection>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="批次号">
          <span class="label-required after" slot="label">批次号</span>
          <el-form-item
            label=""
            required
            label-width="0"
            class="w100"
            prop="categoryMsg.batchNo"
          >
            <el-select v-model="categoryMsg.batchNo" placeholder="请选择">
              <el-option
                v-for="(item, index) in batchList"
                :key="index"
                :label="item.batchNum"
                :value="item.batchNum"
                @click.native="categoryMsg.totalWeight = item.storageNum"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item label="原料重量(KG)">
          <span class="label-required after" slot="label">原料重量(KG)</span>
          <el-form-item
            label=""
            required
            label-width="0"
            class="w100"
            prop="categoryMsg.totalWeight"
            ><el-input
              v-model="categoryMsg.totalWeight"
              placeholder="请输入"
            ></el-input> </el-form-item
        ></el-descriptions-item>
        <el-descriptions-item label="质检项" :span="1">
          <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=""
            label-width="0"
            class="w100"
            required
            prop="productInfo.standardNum"
            ><el-input
              class="w100"
              v-model.number="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"
              placeholder="请输入"
              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"
            placeholder="请输入"
            :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>

      <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="设备位置">{{
          workReportDeviceList.path
        }}</el-descriptions-item>
        <el-descriptions-item label="操作" :span="2"
          ><el-link type="primary" @click="getEquip"
            >选择设备</el-link
          ></el-descriptions-item
        >
        <el-descriptions-item label="模具编码/名称"
          ><el-input
            class="w100"
            :value="`${moduleMsg.code}/${moduleMsg.name}`"
            @click.native="getCategory('5', 'moduleMsg')"
          ></el-input
        ></el-descriptions-item>
        <el-descriptions-item label="规格">{{
          moduleMsg.specification
        }}</el-descriptions-item>
        <el-descriptions-item label="型号">{{
          moduleMsg.model
        }}</el-descriptions-item>
        <el-descriptions-item label="冲压次数" :span="4"
          ><el-input
            placeholder="请输入"
            v-model="moduleMsg.extraField.stampingTimes"
          ></el-input
        ></el-descriptions-item>
        <!-- <el-descriptions-item label="周转车编码/名称"
          ><el-input
            :value="`${boatMsg.code}/${boatMsg.name}`"
            @click.native="getCategory('8', 'boatMsg')"
          ></el-input
        ></el-descriptions-item>
        <el-descriptions-item label="规格">{{
          boatMsg.specification
        }}</el-descriptions-item>
        <el-descriptions-item label="槽数">{{ slotNum }}</el-descriptions-item>
        <el-descriptions-item label="数量"
          ><el-input
            placeholder="请输入"
            v-model="boatMsg.extraField.boatNum"
          ></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-card>
    <equipmentDailog ref="equipmentRef" :taskId="taskInfo.id" />
    <materialDialog
      ref="materialRef"
      :params="{
        taskInstanceId: taskInfo.id,
        versionId: infoData.produceVersionId
      }"
    />

    <catogaryDialog ref="catogaryDialogRef" />
    <carDialog ref="carDialogRef" />
    <handleDialog ref="handleDialogRef" />
  </el-form>
</template>

<script>
  import { realTimeStorage } from '@/api/mainData';
  import personSelectRemote from '@/components/CommomSelect/person-select-remote';
  import equipmentDailog from '@/components/EquipmentDailog/report-equipment';
  import materialDialog from '../materialDialog.vue';
  import catogaryDialog from '../catogaryDialog.vue';
  import carDialog from '../carDialog.vue';
  import { reportCount, getSoltNum } from '@/api/produceOrder';
  import { multiply } from '@/utils/math';
  import handleDialog from './components/handleDialog';
  import dayjs from 'dayjs';
  export default {
    components: {
      handleDialog,
      personSelectRemote,
      equipmentDailog,
      materialDialog,
      carDialog,
      catogaryDialog
    },
    props: {
      infoData: {
        type: Object,
        default: () => ({})
      },
      formData: {
        type: Object,
        default: () => ({})
      },
      taskInfo: {
        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'
          }
        ],
        carList: [],
        categoryMsg: {
          batchNo: '',
          number: '',
          position: '',
          totalWeight: '',
          brandNum: '',
          sourceCategoryId: '',
          rootCategoryLevelId: '1',
          name: '',
          code: ''
        },
        workReport: {
          qualityItem: '',
          qualityStandard: '',
          executorId: '',
          executorJobNum: '',
          executeTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          remark: '',
          productInfo: {
            standardNum: '',
            byProductWeight: '',
            standardWeight: '',
            noStandardNum: '',
            noStandardWeight: ''
          }
        },
        // 设备
        workReportDeviceList: {
          code: '',
          name: '',
          path: '',
          model: '',
          rootCategoryLevelId: '',
          specification: ''
        },
        countMsg: {},
        // 模具信息
        moduleMsg: {
          code: '',
          name: '',
          path: '',
          model: '',
          rootCategoryLevelId: '',
          specification: '',
          extraField: {
            stampingTimes: ''
          }
        },
        // 舟皿信息
        boatMsg: {
          code: '',
          name: '',
          path: '',
          model: '',
          rootCategoryLevelId: '',
          specification: '',
          extraField: {
            boatNum: ''
          }
        },
        batchList: [],
        disposeOrderList: [],
        slotNum: ''
      };
    },
    watch: {
      taskInfo: {
        immediate: true,
        handler() {
          if (this.taskInfo.code) {
            this.getReportCount();
          }
        }
      },
      formData: {
        immediate: true,
        handler() {
          if (this.formData.dateType == 2) {
            this.$set(
              this.workReport,
              'executeTime',
              this.formData.appointTime
            );
          }
        }
      },
      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
              }
            );
          }
        }
      }
    },
    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) => {
          if (id == '8') {
            getSoltNum(res.id).then((r) => {
              this.slotNum = r.slotNum;
            });
          }
          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.boatNum = '';
          }
        });
      },
      getMaterial() {
        this.$refs.materialRef.open(this.categoryMsg, (res) => {
          this.categoryMsg.name = res.categoryName;
          this.categoryMsg.code = res.categoryCode;
          this.categoryMsg.sourceCategoryId = res.id;
          this.categoryMsg.brandNum = res.brandNum;
          this.categoryMsg.factoryCode = res.factoryCode;

          if (this.categoryMsg.position) {
            this._realTimeStorage();
          }
        });
      },
      warehuseChange() {
        if (this.categoryMsg.code) {
          this._realTimeStorage();
        }
      },
      _realTimeStorage() {
        this.categoryMsg.batchNo = '';
        realTimeStorage({
          position: this.categoryMsg.position,
          categoryCode: this.categoryMsg.code,
          factoryCode: this.categoryMsg.factoryCode || '14T1'
        }).then((res) => {
          this.batchList = 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;
          }
        );
      },
      async getReportCount() {
        const res = await reportCount({
          taskCode: this.taskInfo.code,
          workOrderId: this.infoData.id
        });

        this.countMsg = res;
      },
      report(fun) {
        this.$refs.formRef.validate((value, error) => {
          if (value) {
            if (!this.workReportDeviceList.code) {
              return this.$message.error('请选择设备');
            }
            if (!this.carList.length) {
              return this.$message.error('请选择周转车');
            }

            this.$confirm('是否确定要报工?', '提示').then(() => {
              const workReportDeviceList = this.carList;
              if (this.workReportDeviceList.code) {
                workReportDeviceList.push(this.workReportDeviceList);
              }
              if (this.moduleMsg.code) {
                workReportDeviceList.push(this.moduleMsg);
              }

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

<style lang="scss" scoped>
  .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;
    }
  }
</style>
