<template>
  <div>
    <!-- 质检工序 -->
    <div class="top_fixed">
      <el-button type="primary" size="mini" @click="save(2, 'all')"
        >确认</el-button
      >
      <!-- <el-button type="primary" size="mini" @click="removeCacheFn('all')">清空缓存</el-button>
        <el-button v-if="taskObj.type == 1" type="primary" size="mini" @click="save(1, 'all')">缓存</el-button> -->
    </div>

    <div class="job_box">
      <div
        v-for="(item, index) in List"
        :key="index"
        class="card_box"
        v-if="isLoad"
      >
        <div class="title_box rx-bc">
          <div class="name">工单信息 </div>

          <div class="rx-bc">
            <el-button
              type="primary"
              size="mini"
              @click="openPicking(item.id, item)"
              >手动添加</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="openPicking(item.id, item, 1)"
              >周转车质检</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="openQuality(item.id, item)"
              >取样</el-button
            >
          </div>
        </div>
        <!-- // 工单信息 -->

        <workOrderBom :item="item"></workOrderBom>
        <div>
          <div class="title_box rx-bc">
            <div class="name">取样时间 </div>
          </div>
          <el-date-picker
            v-model="item.executorTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期"
          >
          </el-date-picker>
          <!--  -->
        </div>
        <div>
          <div class="title_box rx-bc">
            <div class="name">在制品 </div>
          </div>

          <!-- <div class="title_box rx-bc"> -->
          <!-- <div class="material">
            <div class="content_table">
              <div class="item rx-sc">
                <div class="rx ww50">
                  <div class="lable rx-cc">工序名称</div>
                  <div class="content">
                    {{ item?.product?.name }}
                  </div>
                </div>
                <div class="rx ww50">
                  <div class="lable rx-cc">合格数量</div>
                  <div class="content"
                    >{{ item?.product?.feedQuantity }}{{ item?.product?.unit }}
                  </div>
                </div>
              </div>
            </div>
          </div> -->

          <div class="material">
            <div class="content_table">
              <div class="item rx-sc">
                <div class="rx ww50">
                  <div class="lable rx-cc">名称</div>
                  <div class="content">
                    {{ item.product.name + '-在制品' }}
                  </div>
                </div>

                <div class="rx ww50">
                  <div class="lable rx-cc">牌号</div>
                  <div class="content">{{ item.product.brandNu }}</div>
                </div>
              </div>

              <div class="item rx-sc">
                <div class="rx ww50">
                  <div class="lable rx-cc">型号</div>
                  <div class="content">{{ item.product.modelType }}</div>
                </div>
                <div class="rx ww50">
                  <div class="lable rx-cc">数量</div>
                  <div class="content rx-sc">
                    <div v-if="item.product.extInfo">
                      {{ item.product.extInfo.sourceQuantity || 0 }}
                      {{ item.unit }}</div
                    >
                  </div>
                </div>
              </div>

              <div class="item rx-sc">
                <div class="rx ww50">
                  <div class="lable rx-cc">投料数量</div>
                  <div class="content content_num rx-sc">
                    <el-input
                      size="mini"
                      v-model="item.product.feedQuantity"
                      type="digit"
                      @input="maxFeedQuantity(item)"
                      placeholder="请输入投料数量"
                    />
                  </div>
                </div>
              </div>

              <!-- <div class="del_box">
                <el-link
                  type="danger"
                  icon="el-icon-delete"
                  @click="getDelete(index)"
                ></el-link>
              </div> -->
            </div>
          </div>
          <!-- </div> -->
        </div>

        <paramBom
          v-if="item.paramDetailList.length != 0"
          :list="item.paramDetailList"
        ></paramBom>

        <!-- //报工信息 -->

        <!-- // 设备信息、 -->
        <deviceBom
          v-if="item.equipmentList.length != 0"
          :list="item.equipmentList"
        ></deviceBom>

        <palletBom
          v-if="item.palletList.length != 0"
          :list="item.palletList"
        ></palletBom>

        <revolvingDiskBom
          v-if="item.revolvingDiskList.length > 0"
          pattern="job"
          :list="objData.revolvingDiskList"
        >
        </revolvingDiskBom>

        <!-- 报告信息 -->

        <!-- 取样列表 -->
        <semiProductJobBom
          v-if="item.semiProductList && item.semiProductList.length != 0"
          :list="item.semiProductList"
          :equipmentList="item.equipmentList"
          :singleReport="item.singleReport"
          :item="item"
        ></semiProductJobBom>
        <!-- <newQualityTesting ref="newQualityTestingRef" :singleReport="item.singleReport"></newQualityTesting> -->

        <!-- 物料清单 -->
        <instanceBom
          v-if="item.instanceList.length != 0"
          :list="item.instanceList"
          :equipmentList="item.equipmentList"
          :currentTaskDiagram="item.currentTaskDiagram"
          :workInfo="item"
        >
        </instanceBom>

        <!-- 周转车 -->
        <turnoverBom
          v-if="item.turnover.length != 0"
          :wordItem="item"
          :list="item.turnover"
          pattern="feed"
        >
        </turnoverBom>
      </div>
    </div>

    <!-- 选择物料弹窗 -->
    <pickingList
      :isType="type"
      ref="pickingListRef"
      @allSelection="allSelection"
    ></pickingList>

    <el-dialog
      title="质检数"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="质检取样数">
          <el-input v-model="form.quantity"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="asyncgetQualityParam"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { listByIdsReport } from '@/api/produce/job';
  import { getWarehouseList } from '@/api/produce/index';
  import {
    qualityParam,
    batchSave,
    jobSave,
    saveCache,
    getCache,
    removeCache,
    mesWorkorderList
  } from '@/api/produce/workOrder';
  import pickingList from '../picking/pickingList.vue';
  import packagingGrouping from './components/packagingGrouping.vue';
  import workOrderBom from '../feeding/components/workOrderBom.vue';
  import paramBom from '../feeding/components/paramBom.vue';
  import jobBom from './components/jobBom.vue';
  import deviceBom from '../feeding/components/deviceBom.vue';
  import modelBom from '../feeding/components/modelBom.vue';
  import palletBom from './components/palletBom.vue';
  import revolvingDiskBom from '../feeding/components/revolvingDiskBom.vue';
  import oneJobQualityBom from './components/oneJobQualityBom.vue';
  import oneJobQualityBomPL from './components/oneJobQualityBomPL.vue';
  import newQualityTesting from './components/newQualityTesting.vue';
  // src\views\produce\components\jobBooking\components\semiProductJobBom.vue
  import semiProductJobBom from '@/views/produce/components/jobBooking/components/semiProductJobBom.vue';
  import semiProductJobBomPL from './components/semiProductJobBomPL.vue';
  import semiProductJobBomQT from './components/semiProductJobBomQT.vue';
  import instanceBom from './components/instanceBom.vue';

  import byProductBom from './components/byProductBom.vue';
  import turnoverBom from './components/turnoverBom.vue';
  import aridRegion from '../feeding/components/aridRegion.vue';
  import packingBom from './components/packingBom.vue';
  import packingTgBom from './components/packingTgBom';

  export default {
    components: {
      pickingList,
      packagingGrouping,
      workOrderBom,
      newQualityTesting,
      instanceBom,
      paramBom,
      jobBom,
      deviceBom,
      modelBom,
      palletBom,
      revolvingDiskBom,
      oneJobQualityBom,
      oneJobQualityBomPL,
      semiProductJobBomQT,
      semiProductJobBom,
      semiProductJobBomPL,
      byProductBom,
      turnoverBom,
      aridRegion,
      packingBom,
      packingTgBom
    },
    props: {
      workListIds: {
        type: Array,
        default() {
          return [];
        }
      },
      singleReport: {
        default: null
      }
    },

    computed: {
      taskObj() {
        return this.$store.state.user.taskObj;
      }
    },

    data() {
      return {
        dialogVisible: false,
        List: [],
        idsList: [],
        type: 'job',
        isLoad: false,
        form: {
          quantity: '',
          workOrderId: '',
          taskId: '',
          areaQuantity: []
        },
        warehouseList: [],

        loading: null
      };
    },

    computed: {
      taskObj() {
        return this.$store.state.user.taskObj;
      },

      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },

    watch: {
      workListIds: {
        handler(val) {
          this.getList(val);
        },
        deep: true,
        immediate: true
      }
    },

    created() {
      this.getWarehouseListFn();
    },

    methods: {
      // 质检弹窗
      async openQuality(v, i) {
        this.form.workOrderId = v;
        this.form.taskId = i.currentTaskDiagram.taskId;
        this.dialogVisible = true;
      },

      handleClose() {
        this.form = {
          quantity: '',
          workOrderId: '',
          taskId: '',
          areaQuantity: []
        };
        this.dialogVisible = false;
      },
      async asyncgetQualityParam() {
        const res = await qualityParam(this.form);

        console.log(this.List, '666666', this.$refs.newQualityTestingRef);
        // this.$nextTick(() => {
        //     this.$refs.newQualityTestingRef.open(res)

        //     this.dialogVisible = false;
        // })
        // this.List[0].semiProductList = res;
        this.$set(this.List[0], 'semiProductList', res);
        // console.log(this.List[0], 'this.List[0]');

        this.List[0].semiProductList = this.List[0].semiProductList.map(
          (item) => {
            item.workReportInfo = {
              formingNum: null,
              formingWeight: null,
              formedNum: null,
              formedWeight: null,
              taskId: this.taskObj.id,
              executorTime: null
            };

            item.notFormedList = [
              {
                notFormedNum: null,
                notFormedWeight: null,
                weightUnit: res.weightUnit,
                unit: res.unit,
                warehouseId: null // 处置 仓库id
              }
            ];

            return {
              ...item
            };
          }
        );

        console.log(this.List[0], 'this.List[0]');

        // this.$refs.newQualityTestingRef[0].open(this.List[0].semiProductList);
        this.dialogVisible = false;
      },

      checkPack() {
        this.$refs.packagingGroupingRef[0].getData();
      },

      getList(ids) {
        this.idsList = ids || [];
        let param = {
          ids: ids,
          taskId: this.taskObj.id
        };
        this.isLoad = false;
        mesWorkorderList(param)
          .then((res) => {
            this.List = res.map((obj) => {
              obj.workOrderId = obj.id;

              if (!Object.prototype.hasOwnProperty.call(obj, 'turnover')) {
                obj['turnover'] = [];
              }
              if (
                !Object.prototype.hasOwnProperty.call(obj, 'aridRegionList')
              ) {
                obj['aridRegionList'] = [];
              }

              if (!Object.prototype.hasOwnProperty.call(obj, 'instanceList')) {
                obj['instanceList'] = [];
              }

              if (!Object.prototype.hasOwnProperty.call(obj, 'palletList')) {
                obj['palletList'] = [];
              }

              if (
                !Object.prototype.hasOwnProperty.call(obj, 'revolvingDiskList')
              ) {
                obj['revolvingDiskList'] = [];
              }

              if (obj.palletList.length > 0) {
                obj.palletList = obj.palletList.map((m) => {
                  return {
                    hideKc: true, // 不显示库存
                    quantity: m.feedQuantity,
                    ...m
                  };
                });
              }

              if (this.taskObj.type == 6 && this.clientEnvironmentId == 3) {
                obj.semiProductList = obj.pickOutInList;
              }

              if (
                this.clientEnvironmentId == 3 &&
                obj.singleReport == 0 &&
                this.taskObj.type != 6
              ) {
                obj.semiProductList.map((a) => {
                  a.extInfo.batchReportInfo = [
                    {
                      allFeedQuantity: '',
                      allReportWeight: '',
                      taskId: '',
                      taskName: ''
                    }
                  ];

                  a.extInfo.notBatchReportInfo = [
                    {
                      allFeedQuantity: '',
                      notType: '',
                      taskId: '',
                      taskName: '',
                      notReason: ''
                    }
                  ];

                  return {
                    a
                  };
                });
                obj.semiProductList = JSON.parse(
                  JSON.stringify(obj.semiProductList)
                );
              }

              obj.paramDetailList.map((m) => {
                if (m.extInfo.textType == 5) {
                  m.remainingTime = m.extInfo.remainingTime;
                }
                return {
                  ...m.extInfo
                };
              });

              if (this.taskObj.id) {
                obj.taskId = this.taskObj.id;
                obj.taskName = this.taskObj.name;
              }
              // console.log(obj, 444);

              return {
                ...obj
              };
            });

            console.log(this.List, 'List;istlist');
          })
          .finally(() => {
            this.isLoad = true;

            if (this.taskObj.type == 1) {
              this.getCacheFn();
            }
          });
      },

      openPicking(id, item, n) {
        console.log(item.turnover);

        let listArr = JSON.parse(JSON.stringify(item));

        if (n && listArr.turnover.length) {
          let arr = [],
            isArr = [];

          listArr.turnover.forEach((v) => {
            console.log(v.extInfo, '555');
            isArr = v.extInfo.positionList.filter((d) => d.sampleNum);
          });
          if (!isArr.length) {
            return this.$message.error('请输入取样数');
          }

          listArr.turnover.forEach((v) => {
            v.extInfo.positionList.map((d) => {
              if (d.sampleNum) {
                d.quantity = d.sampleNum;
                arr.push(d);
              }
            });
          });

          //    console.log(arr,'88888');
          this.form.workOrderId = id;
          this.form.taskId = item.currentTaskDiagram.taskId;
          this.form.areaQuantity = arr;

          this.asyncgetQualityParam();
        } else {
          this.$refs.pickingListRef.open(id, item);
        }
      },

      allSelection(id, selectList) {
        this.List.forEach((m) => {
          if (m.workOrderId == id) {
            let modelList = []; // 模具
            let instanceList = []; // 投料
            let aridRegionList = []; // 干燥区
            let equipmentList = []; // 生产设备
            let palletList = []; // 舟皿
            let revolvingDiskList = []; // 周转盘
            let semiProductList = []; // 半成品
            let turnover = []; //周转车

            selectList.forEach((f) => {
              if (f.rootCategoryLevelId == 4) {
                equipmentList = equipmentList.concat(f);
              }
              if (f.rootCategoryLevelId == 5) {
                modelList = modelList.concat(f);
              } else if (f.rootCategoryLevelId == 1) {
                instanceList = instanceList.concat(f);
              } else if (f.rootCategoryLevelId == 11) {
                aridRegionList = aridRegionList.concat(f);
              } else if (f.rootCategoryLevelId == 7) {
                turnover = turnover.concat(f);
              } else if (f.rootCategoryLevelId == 8) {
                palletList = palletList.concat(f);
              } else if (f.rootCategoryLevelId == 26) {
                revolvingDiskList = revolvingDiskList.concat(f);
              } else if (
                [23, 2, 9, 28].includes(Number(f.rootCategoryLevelId))
              ) {
                semiProductList = semiProductList.concat(f);
              }
            });

            this.$set(m, 'modelList', modelList);
            this.$set(m, 'instanceList', instanceList);
            this.$set(m, 'aridRegionList', aridRegionList);
            this.$set(m, 'equipmentList', equipmentList);
            this.$set(m, 'turnover', turnover);
            this.$set(m, 'palletList', palletList);
            this.$set(m, 'revolvingDiskList', revolvingDiskList);
            this.$set(m, 'semiProductList', semiProductList);

            this.$forceUpdate();
          }
        });
      },

      async save(type) {
        // this.List[0].turnover &&
        //     this.List[0].turnover.forEach((f) => {
        //         if (
        //             f.extInfo &&
        //             f.extInfo.positionList &&
        //             f.extInfo.positionList.length > 0
        //         ) {

        //             let arr = f.extInfo.positionList.filter((o) => o.sampleNum >= 1)
        //             if (arr.length) {
        //                 uni.showToast({
        //                     icon: "none",
        //                     title: "请先点击周转车质检",
        //                 });
        //             }
        //         }
        //     });

        batchSave(this.List)
          .then((res) => {
            this.$message.success('质检成功');
            this.getList(this.idsList);
          })
          .catch(() => {})
          .finally(() => {
            setTimeout(function () {
              // this.loading.close();
            }, 3000);
          });
      },

      checkRecycle() {
        this.loading.close();
        return new Promise((resolve) => {
          this.$confirm('是否跳过副产品回收处置！', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              resolve(true);
            })
            .catch(() => {
              resolve(false);
            });
        });
      },

      checkCache(type) {
        return new Promise((resolve) => {
          if (type == 1) {
            saveCache(this.List).then((rr) => {
              this.$message.success('缓存成功');
              this.loading.close();
            });
            resolve(false);
          } else if (type == 2) {
            resolve(true);
          }
        });
      },

      getCacheFn() {
        let parma = {
          workOrderIds: this.idsList,
          taskId: this.taskObj.id,
          type: 1
        };

        getCache(parma).then((res) => {
          console.log(res);
        });
      },

      removeCacheFn(type) {
        this.$confirm('是否清空缓存', '缓存')
          .then(() => {
            let parma = {
              workOrderIds: type == 'all' ? this.idsList : [type],
              taskId: this.taskObj.id,
              type: 1
            };
            removeCache(parma).then((res) => {
              this.$message.success('已经清空缓存');
              this.getList(this.idsList);
            });
          })
          .catch(() => {});
      },

      maxFeedQuantity(data) {
        console.log(data, 'this.data');
        if (data.product.feedQuantity > data.formingNum) {
          this.$set(data.product, 'feedQuantity', data.formingNum);
        }
      },

      getWarehouseListFn() {
        getWarehouseList().then((res) => {
          this.warehouseList = res.data;
        });
      }
    }
  };
</script>

<style scoped lang="scss">
  .top_fixed {
    width: 100%;
    height: 40px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .title_box {
    padding: 10px 0;

    .name {
      font-size: 14px;
      font-style: normal;
      font-weight: 400;
      color: #157a2c;
      padding-left: 5px;
      position: relative;

      &:before {
        position: absolute;
        content: '';
        left: 0px;
        top: 0px;
        bottom: 0px;
        width: 2px;
        height: 14px;
        background: #157a2c;
        margin: auto;
      }
    }
  }

  .job_box {
    margin-top: 6px;
    width: 100%;
    height: calc(100vh - 70px - 50px - 80px - 60px);
    overflow-y: scroll;
    overflow-x: hidden;
  }

  .card_box {
    background: #fff;
    padding: 8px;
    border-radius: 2px;
  }
</style>
