<template>
  <view class="mainBox">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="新增报损报溢"
      @clickLeft="back"
    >
    </uni-nav-bar>

    <u-form
      labelPosition="left"
      :model="formData"
      :rules="rules"
      ref="formRef"
      labelWidth="260"
      labelAlign="right"
      class="baseForm"
    >
      <u-form-item label="报损报溢编码" borderBottom prop="code">
        <u-input
          :value="formData.code"
          disableColor="#ffffff"
          placeholder="请选择"
          disabled
          type="select"
        />
      </u-form-item>
      <u-form-item label="名称" class="required-form" borderBottom prop="name">
        <u-input v-model="formData.name" placeholder="请输入" type="text" />
      </u-form-item>
      <u-form-item
        label="报损报溢部门"
        class="required-form"
        prop="bizScene"
        borderBottom
      >
        <u-input
          v-model="formData.reportDeptName"
          disableColor="#ffffff"
          placeholder="请选择"
          disabled
          type="select"
        />
      </u-form-item>
      <u-form-item
        label="报损报溢人"
        class="required-form"
        prop="reportName"
        borderBottom
      >
        <u-input
          :value="formData.reportName"
          disableColor="#ffffff"
          placeholder="请选择"
          disabled
          type="select"
        />
      </u-form-item>
      <u-form-item label="审核人部门" prop="verifyDeptName" borderBottom>
        <u-input
          :value="formData.verifyDeptName"
          disableColor="#ffffff"
          placeholder="请选择"
          disabled
          type="select"
          @click.native="$refs.treePicker._show()"
        />
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="审核人" prop="auditId" borderBottom>
        <picker
          @change="(e) => handlePicker(e, userList, 'auditId', 'auditName')"
          :value="pickerIndex"
          :range="userList"
          range-key="name"
        >
          <u-input
            :value="formData.auditName"
            disableColor="#ffffff"
            placeholder="请选择"
            disabled
            type="select"
          />
        </picker>
        <u-icon slot="right" name="arrow-right"></u-icon>
      </u-form-item>
      <u-form-item label="备注" prop="remark" borderBottom>
        <u-textarea
          confirmType="done"
          :maxlength="-1"
          height="80"
          v-model="formData.remark"
          placeholder="请输入"
        ></u-textarea>
      </u-form-item>
    </u-form>

    <uni-section title="报损报溢明细" type="line">
      <template v-slot:right>
        <text class="text-primary" @click="workorderSelect">选择盘点工单</text>
      </template>
      <view class="order-box">盘点工单{{ formData.workOrderCode }}</view>
      <view
        v-for="(item, index) in formData.list"
        :key="index"
        class="list-card"
      >
        <view class="status" :style="{ color: _getStatus(item.status).color }">
          <text>{{ _getStatus(item.status).name }}</text>
          <text
            >数量：{{
              [1, 2].includes(item.status) ? "-1" : `+${item.checkNum || 0}`
            }}</text
          >
        </view>
        <view class="row first">
          <view class="col" style="width: 100%">
            <text class="main">{{ item.name }}</text>
            {{ item.code }}
          </view>
          <view class="col" style="width: 100%">
            <text class="main">货位：</text>
            {{ item.warehouseName }}-{{ item.reservoirName }}-{{
              item.goodsShelfName
            }}-{{ item.goodsAllocationName }}
          </view>
        </view>
        <view class="row">
          <view class="col">
            <text class="label">批次号：</text>
            {{ item.batchNo }}
          </view>
          <view class="col">
            <text class="label">类型：</text>
            {{ getDictValue("物品类型", item.productType) }}
          </view>
          <view class="col" v-for="(itm, index) in tableHeader" :key="index">
            <text class="label">{{ itm.label }}：</text>
            {{ item[itm.prop] }}
          </view>
          <view class="col" v-if="!item.isUnpack">
            <text class="label">最小单元：</text>
            {{ item.unit }}/{{ item.minPackUnit }}
          </view>
        </view>
        <uni-icons
          type="trash"
          size="30"
          class="del"
          @click="delRow(index)"
        ></uni-icons>
      </view>
    </uni-section>

    <view class="footBox">
      <u-button type="success" @click="handleSubmit">提交</u-button>
    </view>

    <ba-tree-picker
      ref="treePicker"
      :multiple="false"
      @select-change="deptConfirm"
      key="dept"
      title="选择部门"
      :localdata="deptList"
      valueKey="code"
      textKey="name"
      childrenKey="children"
    />
  </view>
</template>

<script>
import { post, postJ, get, getJ } from "@/utils/api.js";
import {
  getDict,
  wh_equStatus,
  getDictName,
  warehousingType,
} from "../enum.js";
import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue";
import { getRuleNo } from "@/utils/utils.js";
import dictMxins from "@/mixins/dictMixins";
export default {
  components: { baTreePicker },
  mixins: [dictMxins],
  data() {
    return {
      warehousingType,
      getDictName,
      pickerIndex: 0,
      deptList: [],
      userList: [],
      formData: {
        code: getRuleNo("BS"),
        auditId: "",
        auditName: "",
        verifyDeptCode: "",
        verifyDeptName: "",
        workOrderCode: "",
        list: [],
      },
      isMaterial: true,
      rules: {
        // name: {
        //   type: 'string',
        //   required: true,
        //   message: '请输入名称',
        //   trigger: ['blur']
        // }
      },
    };
  },
  onLoad({ id }) {
    this.requestDict("物品类型");
    if (id) {
      this.getDetail(id);
    } else {
      const userInfo = uni.getStorageSync("userInfo");

      this.formData.reportName = userInfo.name;
      this.formData.reportId = userInfo.id;
      this.formData.reportDeptName = userInfo.dept.name;
      this.formData.reportDeptId = userInfo.dept.code;
    }

    this.getDept();
    uni.$off("getWorkorder");
    uni.$on("getWorkorder", (data) => {
      if (data?.id) {
        this.formData.workOrderCode = data.workOrderCode;

        this.isMaterial = data.assetDict?.code === 3;
        this._getAbnormaldetailList(data.id);
      }
    });
  },
  computed: {
    tableHeader() {
      if (this.formData.list?.length) {
        return this.getTableHeader(this.formData.list[0].assetTypeDict);
      }
      return [];
    },
  },
  methods: {
    getTableHeader(selectEquiType) {
      switch (+selectEquiType) {
        case 3:
          return [{ label: "牌号", prop: "assetBrand" }];
        case 8:
          return [
            { label: "型号", prop: "assetSku" },
            { label: "规格", prop: "specification" },
          ];
        case 4:
          return [
            { label: "牌号", prop: "assetBrand" },
            { label: "型号", prop: "assetSku" },
          ];
        case 5: //'周转车'
          return [
            { label: "规格", prop: "specification" },
            {
              label: "材质",
              prop: "texture",
              formatter(row) {
                if (!row?.extendField) return "";
                const extendField = JSON.parse(row.extendField);
                return extendField.texture;
              },
            },
            {
              label: "长宽高",
              prop: "",
              formatter(row) {
                if (!row?.extendField) return "";
                const extendField = JSON.parse(row.extendField);
                return `${extendField.length || "-"}*${
                  extendField.width || "-"
                }*${extendField.high || "-"}`;
              },
            },
          ];
        case 2: //'舟皿'
          return [
            { label: "规格", prop: "specification" },
            { label: "型号", prop: "assetSku" },
            {
              label: "长宽高",
              prop: "",
              formatter(row) {
                if (!row?.extendField) return "";
                const extendField = JSON.parse(row.extendField);
                return `${extendField.length || "-"}*${
                  extendField.width || "-"
                }*${extendField.high || "-"}`;
              },
            },
          ];
        case 1: //'设备'
          return [
            { label: "型号", prop: "assetSku" },
            { label: "规格", prop: "specification" },
          ];
        case 6: //'模具'
          return [
            { label: "牌号", prop: "assetBrand" },
            { label: "型号", prop: "assetSku" },
            {
              label: "收缩系数",
              prop: "",
              formatter(row) {
                if (!row?.extendField) return "";
                const extendField = JSON.parse(row.extendField);
                return extendField.shrinkageCoefficient;
              },
            },
          ];
        case 7: //'备品备件'
          return [
            { label: "规格", prop: "specification" },
            { label: "型号", prop: "assetSku" },
          ];
      }

      return [];
    },
    _getStatus: getDict(wh_equStatus),
    workorderSelect() {
      uni.navigateTo({
        url: "/pages/warehouse/reportLoss/workorderSelected",
      });
    },
    async getDetail(id) {
      const res = await get(this.apiUrl + `/breakag/info/${id}`);
      if (res?.success) {
        this.formData = res.data;
      }
    },
    // 工单详情
    async _getAbnormaldetailList(workOrderId) {
      const res = await postJ(
        this.apiUrl +
          `/repertoryCheck/getAbnormaldetailList?workOrderId=${workOrderId}`
      );
      if (res?.success) {
        this.formData.list = (res.data || []).map((itm) => {
          delete itm.id;
          if ([1, 2].includes(itm.equStatus)) {
            itm.checkNum = 1;
          }

          return {
            ...itm,
            amount: itm.checkNum,
            model: itm.assetSku,
            name: itm.assetName,
            productType: itm.assetTypeDict,
            code: itm.assetCode,
            batch: itm.batchNo,
            num: itm.bucketNum,
            bizTypeId: itm.bizTypeId,
            bizTypeName: itm.bizTypeName,
            status: itm.equStatus,
            unitPrice: itm.univalence,
            minimumUnit: itm.minPackUnit,
          };
        });
      }
    },
    delRow(index) {
      this.formData.list.splice(index, 1);
    },
    async handleSubmit() {
      // this.$refs.formRef.validate().then(async () => {
      if (!this.formData.list?.length) {
        uni.showToast({
          title: "请选择工单！",
          icon: "none",
        });
        return;
      }
      const res = await postJ(this.apiUrl + `/breakag/save`, this.formData);
      if (res?.success) {
        uni.showToast({
          title: "提交成功！",
          icon: "success",
        });

        uni.navigateBack({
          delta: 1,
        });
      }
      // })
    },
    // 抬头下拉信息保存
    handlePicker(e, list, idKey, nameKey) {
      if (idKey) {
        this.formData[idKey] = list[e.detail.value].id;
      }
      if (nameKey) {
        this.formData[nameKey] = list[e.detail.value].name;
      }
    },
    // 部门确认
    deptConfirm(data, name) {
      this.formData.verifyDeptCode = data[0];
      this.formData.verifyDeptName = name;
      this.formData.auditId = "";
      this.formData.auditName = "";

      this.getUser(data[0]);
    },
    // 获取部门
    getDept() {
      get(this.apiUrl + "/main/org/dept/effectiveTree").then((res) => {
        if (res?.success) {
          this.deptList = res.data;
        }
      });
    },

    // 获取人员
    getUser(deptCode) {
      post(this.apiUrl + "/main/user/list", {
        deptCode,
        page: 1,
        size: 9999,
      }).then((res) => {
        if (res?.success) {
          this.userList = res.data.items.map((item) => {
            item.name = item.trueName;
            item.id = item.userId;
            return item;
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.footBox {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.mainBox {
  padding-bottom: 90rpx;

  .order-box {
    color: #7f7f7f;
    background-color: rgba(215, 215, 215, 0.729411764705882);
    line-height: 44rpx;
    border-radius: 44rpx;
    text-align: center;
    font-size: 28rpx;
    margin: 0 20rpx;
  }

  .list-card {
    border-bottom: 6rpx solid #f2f2f2;
    position: relative;
    .status {
      padding: 6rpx 20rpx;
      font-weight: bold;
      font-size: 28rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #f2f2f2;
    }
    .del {
      position: absolute;
      color: $uni-color-order-error !important;
      bottom: 5rpx;
      right: 10rpx;
      font-size: 50rpx !important;
    }
    .row {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      flex-wrap: wrap;
      font-size: 28rpx;
      padding: 10rpx 20rpx;
      color: #7d7d7d;

      &.first {
        color: #000;
        font-size: 28rpx;
        border-bottom: 1rpx solid #f2f2f2;
        .col {
          min-width: 0%;
        }
      }

      .col {
        min-width: 45%;
      }
      .label {
        margin-right: 10rpx;
        display: inline-block;
        width: 180rpx;
        text-align: right;
      }
      .main {
        margin-right: 10rpx;
      }
    }
  }
}
</style>
