<template>
  <view class="mainBox">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="自然干燥-报工"
      @clickLeft="back"
    >
    </uni-nav-bar>
    <uni-section :title="`${workReportArea.name}(${workReportArea.code})`">
      <uni-table border stripe class="time-wrapper">
        <uni-tr>
          <uni-td>自然干燥开始时间</uni-td>
          <uni-td>
            <uni-datetime-picker
              type="datetimesingle"
              :clear-icon="true"
              v-model="workReport.productInfo.heatDryStartTime"
            />
          </uni-td>
        </uni-tr>
        <uni-tr>
          <uni-td>自然干燥计划完成时间</uni-td>
          <uni-td>
            <uni-datetime-picker
              type="datetimesingle"
              :clear-icon="true"
              v-model="workReport.productInfo.heatDryCompleteTime"
            />
          </uni-td>
        </uni-tr>
      </uni-table>
    </uni-section>
    <uni-section title="周转车信息">
      <view class="device">
        <template class="device" v-for="(item, index) in carList">
          <view class="divice-top">
            <view class="top-name">周转车编码</view>
            <view class="content">{{ item.code }}</view>
            <view class="del" @click="handleDelete(index)">删除</view>
          </view>
          <view class="order-wrapper">
            <view v-for="itm in item.orderList" class="order-row">
              <view class="order-col"> 工单编号：{{ itm.code }} </view>
              <view class="order-col"> 产品编码：{{ itm.produceCode }} </view>
              <view class="order-col full">
                <text>合格数量(PCS)</text>
                <uni-easyinput
                  placeholder="请输入"
                  v-model="itm.standardNum"
                ></uni-easyinput>
              </view>
              <view class="order-col full">
                <text>合格重量(KG)</text>
                <uni-easyinput
                  trim="all"
                  type="number"
                  :disabled="true"
                  :value="
                    (itm.standardWeight =
                      itm.standardNum === ''
                        ? ''
                        : multiply(itm.standardNum, itm.productUnitWeight || 1))
                  "
                ></uni-easyinput>
              </view>
              <view class="order-col full">
                <text>不合格数量(PCS)</text
                ><uni-easyinput
                  placeholder="请输入"
                  v-model="itm.noStandardNum"
                ></uni-easyinput>
                <view class="handle" @click="handle(1, itm)">处置</view>
              </view>
              <view class="order-col full">
                <text>不合格品重量(KG)</text
                ><uni-easyinput
                  trim="all"
                  type="number"
                  :disabled="true"
                  :value="
                    (itm.noStandardWeight =
                      itm.noStandardNum === ''
                        ? ''
                        : multiply(
                            itm.noStandardNum,
                            itm.productUnitWeight || 1
                          ))
                  "
                ></uni-easyinput>
              </view>
              <!-- <view class="order-col full">
                <text>副产品（KG）：</text
                ><uni-easyinput
                  placeholder="请输入"
                  v-model="itm.byProductWeight"
                ></uni-easyinput>
                <view class="handle" @click="handle(2, itm)">处置</view>
              </view> -->
            </view>
          </view>

          <!-- <uni-table border stripe>
            <uni-tr>
              <uni-th align="center">工单编号</uni-th>
              <uni-th align="center">产品编码</uni-th>
              <uni-th align="center">合格品</uni-th>
              <uni-th align="center"></uni-th>
              <uni-th align="center"></uni-th>
            </uni-tr>
            <uni-tr v-for="itm in item.orderList">
              <uni-td>{{ itm.code }}</uni-td>
              <uni-td> {{ itm.produceCode }} </uni-td>
              <uni-td>
                <uni-easyinput v-model="itm.standardNum"></uni-easyinput>
              </uni-td>
              <uni-td>
                <uni-easyinput v-model="itm.noStandardNum"></uni-easyinput>
              </uni-td>
              <uni-td>
                <uni-easyinput v-model="itm.byProductWeight"></uni-easyinput>
              </uni-td>
            </uni-tr>
          </uni-table> -->
        </template>
        <view class="addcar" @click="chooseCar">+</view>
      </view>
    </uni-section>
    <!-- <uni-section title="处置信息">
      <view class="device handlebox">
        <view class="device-line">
          <view class="line-title">不合格总数量</view>
          <view class="line-content">
            <uni-easyinput
              trim="all"
              disabled
              disableColor="#ffffff"
              :value="sumOpt.noStandardNum"
            ></uni-easyinput>
            <view class="handle" @click="handle(1)">处置</view>
          </view>
        </view>
        <view class="device-line">
          <view class="line-title">副产品</view>
          <view class="line-content">
            <uni-easyinput
              trim="all"
              disabled
              disableColor="#ffffff"
              :value="sumOpt.byProductWeight"
            ></uni-easyinput>
            <view class="handle" @click="handle(2)">处置</view>
          </view>
        </view>
        <view class="device-line">
          <view class="line-title">备注</view>
          <view class="line-content">
            <uni-easyinput trim="all" v-model="diviceName"></uni-easyinput>
          </view>
        </view>
      </view>
    </uni-section> -->
    <view class="bottom" @click="handleReport">完成报工</view>

    <!-- <locationPopu ref="locationRef"></locationPopu>
    <assetPopu ref="assetRef"></assetPopu>
    <moldPopu ref="moldRef"></moldPopu>
    <materialPopu ref="materialRef"></materialPopu> -->
    <carPopu ref="carRef" @confirm="carConfirm"></carPopu>
    <HandlePop ref="handlePopRef" />
  </view>
</template>

<script>
import carPopu from "../components/carPopu.vue";
import {
  pdaReport,
  getWorkerOrderInfo,
  getTaskListById,
} from "@/api/production/execute";
import HandlePop from "../components/HandlePop.vue";
import dayjs from "dayjs";
import { multiply } from "@/utils/math";
// import locationPopu from "./components/locationPopu.vue";
// import assetPopu from "./components/assetPopu.vue";
// import moldPopu from "./components/moldPopu.vue";
// import materialPopu from "./components/materialPopu.vue";
export default {
  components: {
    HandlePop,
    // locationPopu,
    // assetPopu,
    // moldPopu,
    // materialPopu,
    carPopu,
  },
  data() {
    return {
      diviceName: "",
      carList: [],
      workReportArea: {
        associationType: "1",
        code: "",
        name: "",
        heatUpDuration: "",
      },
      lastTaskCode: "",
      workReport: {
        qualityItem: "",
        workOrderId: "",
        qualityStandard: "",
        executorId: "",
        taskSort: "",
        taskCode: "",
        taskName: "",
        executorJobNum: "",
        executeTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        remark: "",
        productInfo: {
          heatDryCompleteTime: "",
          heatDryStartTime: "",
          standardNum: "",
          byProductWeight: "",
          standardWeight: "",
          noStandardNum: "",
          noStandardWeight: "",
        },
      },
      sumOpt: {},
    };
  },
  onLoad({ name, code, path, id }) {
    this.workReportArea.code = code;
    this.workReportArea.name = name;
    this.workReportArea.path = path;
    this.workReportArea.sourceAreaId = id;
    const userInfo = uni.getStorageSync("userInfo");
    this.workReport.executorId = userInfo?.userId;
    this.workReport.executorJobNum = userInfo?.jobNumber;
  },
  watch: {
    // carList: {
    //   deep: true,
    //   handler() {
    //     this.sumOpt = this.carList.reduce(
    //       (next, pre) => {
    //         let obj = pre.orderList.reduce(
    //           (next, pre) => {
    //             return {
    //               noStandardNum:
    //                 Number(next.noStandardNum) + Number(pre.noStandardNum || 0),
    //               byProductWeight:
    //                 Number(next.byProductWeight) +
    //                 Number(pre.byProductWeight || 0),
    //             };
    //           },
    //           {
    //             noStandardNum: 0,
    //             byProductWeight: 0,
    //           }
    //         );
    //         return {
    //           noStandardNum:
    //             Number(next.noStandardNum) + Number(obj.noStandardNum || 0),
    //           byProductWeight:
    //             Number(next.byProductWeight) + Number(obj.byProductWeight || 0),
    //         };
    //       },
    //       {
    //         noStandardNum: 0,
    //         byProductWeight: 0,
    //       }
    //     );
    //   },
    // },
  },

  methods: {
    multiply,
    chooseCar() {
      this.$refs.carRef.open();
    },
    handleDelete(index) {
      const _this = this;
      uni.showModal({
        title: `确定删除当前周转车`,
        content: "",
        confirmText: "确认",
        success: function (res) {
          if (res.confirm) {
            _this.carList.splice(index, 1);
          }
        },
      });
    },
    async carConfirm(list) {
      const obj = this.carList.map((i) => i.id);

      uni.showLoading();
      try {
        for (const p of list) {
          if (!obj.includes(p.id)) {
            obj.push(p.id);
            p.sourceInstanceId = p.id;
            p.extraField = {};
            const data = await getWorkerOrderInfo(p.code);

            this.$set(
              p,
              "orderList",
              data.map((item) => ({
                ...item,
                standardNum: "",
                noStandardNum: "",
                byProductWeight: "",
              }))
            );

            data.length && this._getTaskListById(data[0].produceVersionId);
            this.$set(this.carList, this.carList.length, p);
          }
        }
      } catch (error) {}
      uni.hideLoading();
    },
    chooseMaterial() {
      this.$refs.materialRef.open();
    },
    chooseAsset() {
      this.$refs.assetRef.open();
    },
    chooseMold() {
      this.$refs.moldRef.open();
    },
    chooseLocation() {
      this.$refs.locationRef.open();
    },
    handle(disposeType, item) {
      this.$refs.handlePopRef.open(disposeType, (data) => {
        data.workOrderCode = item.code;
        data.workOrderId = item.id;

        item.disposeOrderList = [data];
      });
    },
    async _getTaskListById(produceVersionId) {
      if (this.workReport.taskCode) {
        return;
      }
      // 获取工序
      let list = await getTaskListById(produceVersionId);
      list = list.filter((i) => !i.name.includes("工具棒"));
      const index = list.findIndex((i) => i.name.includes("挤压干燥"));
      if (index > -1) {
        this.workReport.taskSort = 88;
        this.workReport.taskCode = list[index].code + "-01";
        this.workReport.taskName = "自然干燥";

        this.lastTaskCode = list[index - 1]?.code;
      }
    },
    async handleReport() {
      if (!this.carList.length) {
        return uni.showToast({
          title: "请选择周转车",
          icon: "none",
        });
      }
      const params = [];

      this.carList.forEach((item) => {
        item.orderList.forEach((ele) => {
          this.workReport.workOrderId = ele.id;
          this.workReport.productInfo.standardNum = ele.standardNum;
          this.workReport.productInfo.standardWeight = ele.standardWeight;
          this.workReport.productInfo.noStandardNum = ele.noStandardNum;
          this.workReport.productInfo.noStandardWeight = ele.noStandardWeight;

          params.push({
            checkState: 1,
            isSapReportState: 0, //sap报工状态(0:不调用SAP接口报工;1:投料;2:报工;3:入库)
            lastTaskCode: this.lastTaskCode,
            disposeOrderList: ele.disposeOrderList,
            workReport: this.workReport,
            workReportArea: this.workReportArea,
            workReportDeviceList: [item],
            // workReportCategoryList: [
            //   {
            //     // batchNo: "",
            //     // number: "",
            //     // totalWeight: "",
            //     rootCategoryLevelId: "9",
            //     brandNum: ele.brandNo,
            //     sourceCategoryId: ele.categoryId,
            //     name: ele.productName,
            //     code: ele.productCode,
            //   },
            // ],
            ...ele,
          });
        });
      });

      const _this = this;
      uni.showModal({
        title: `是否提交报工？`,
        content: "",
        confirmText: "确认",
        success: async function (res) {
          if (res.confirm) {
            try {
              await pdaReport(params);
              uni.showToast({
                title: "报工成功！",
              });

              uni.navigateBack({
                delta: 1,
              });
            } catch (error) {
              uni.showToast({
                title: error,
                icon: "none",
              });
            }
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.time-wrapper .uni-table-td {
  font-size: 28rpx;
}
.order-wrapper {
  padding: 0 20rpx;
  .order-row {
    border-bottom: 1rpx solid #ccc;
    padding-bottom: 20rpx;
    margin-bottom: 20rpx;
  }
  .order-col {
    display: flex;
    align-items: center;
    margin-bottom: 10rpx;
    text {
      margin-right: 20rpx;
      display: inline-block;
      width: 230rpx;
    }

    .uni-easyinput {
      width: 30%;
    }
  }
}
.device {
  width: 100%;
  .divice-top {
    width: 96%;
    height: 60rpx;
    margin: 10rpx auto;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  .divice-number {
    display: flex;
    align-items: center;
    justify-content: space-around;
    margin: 20rpx 0;
    span {
      margin-left: 10rpx;
    }
    view:last-child span {
      color: rgba(112, 182, 3, 1);
    }
  }
  .divice-btm {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: 96%;
    margin: 0 auto;
    .btm-mold {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      width: 60%;
      .content {
        width: 35%;
      }
    }
    .btm-mold.btm-last {
      width: 40%;
      .modle-input {
        margin: 0 10rpx;
      }
    }
  }
  .device-line {
    display: flex;
    align-items: center;
    width: 100%;
    border-bottom: 1rpx solid #ccc;
    // margin-bottom: 20rpx;
    height: 80rpx;
    .line-title {
      width: 30%;
      text-indent: 30rpx;
    }
    .line-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 70%;
      margin-right: 20rpx;
      .content {
        width: 70%;
        margin: 0 20rpx 0 0;
      }
      .content-input {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        width: 40%;
        view {
          margin-left: 10rpx;
        }
      }
      .line-right {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        .right-minus {
          width: 80rpx;
          height: 51rpx;
          text-align: center;
          line-height: 51rpx;
          color: #fff;
          background: #f59a23;
        }
        .right-add {
          width: 80rpx;
          height: 51rpx;
          text-align: center;
          line-height: 51rpx;
          color: #fff;
          background: #70b603;
          margin-left: 10rpx;
        }
        .right-choose.u-button--info {
          border-color: #70b603;
          color: #70b603;
        }
      }
    }
  }
  .addcar {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 120rpx;
    color: #ccc;
    font-weight: bold;
    line-height: 80rpx;
  }
  .content {
    width: 40%;
    border: 1rpx solid #ccc;
    border-radius: 8rpx;
    line-height: 60rpx;
    height: 60rpx;
    margin: 0 20rpx;
  }
  .choose {
    background: rgba(112, 182, 3, 1);
    color: #fff;
    padding: 10rpx 20rpx;
    border-radius: 8rpx;
  }
  .del {
    background: rgba(236, 128, 141, 1);
    color: #fff;
    padding: 10rpx 20rpx;
    border-radius: 8rpx;
  }
  .handle {
    background: rgba(112, 182, 3, 1);
    color: #fff;
    padding: 10rpx 20rpx;
    border-radius: 8rpx;
    margin-left: 60rpx;
  }
}
.handlebox {
  padding-bottom: 130rpx;
}
.bottom {
  width: 100%;
  height: 90rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  bottom: 0;
  left: 0;
  font-size: 36rpx;
  color: #fff;
  background: #4b7902;
}
</style>
