<template>
  <div style="width: 100%; padding: 0px 15px">
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="formDom">
      <template #commodity>
        <div style="width: 100%">
          <el-table :data="formData.data.outboundRecordList" style="width: 100%; ">

            <el-table-column label="商品图片" width="80">
              <template #default="{ row }">
                <div v-if="row.fileUrl">
                  <img :src="row.fileUrl" class="pic" @click="openImg(row.fileUrl)" />
                </div>
                <div v-else></div>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" min-width="150" />
            <el-table-column prop="productCode" label="商品编码" width="200" />
            <el-table-column label="规格尺寸 (cm)" width="130">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  {{row.productLength}} * {{row.productWidth}} * {{row.productHeight}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="productColor" label="颜色" width="150" />
            <el-table-column prop="productFrontalTexture" label="纹路" width="130"
                             :formatter="(row) => dictKeyValue(row.productFrontalTexture, frontLinesData)" />
            <el-table-column prop="productNetWeight" label="净重" width="100" />
            <el-table-column prop="productUnit" label="单位" width="100" />
            <el-table-column label="订单数量" width="100" prop="orderQuantity" />
            <el-table-column label="单价" width="100" prop="price" />
            <el-table-column label="已出库数量" width="100" prop="saleOutboundQuantity" fixed="right" />
            <el-table-column prop="quantity" label="出库数量" width="140" fixed="right">
              <template #default="{ row, $index }">
                <el-form-item :prop="'outboundRecordList.' + $index + '.quantity'" :rules="rules.quantity" :inline-message="true" class="margin-b-0">
                  <el-input-number onmousewheel="return false;" v-model="row.quantity" placeholder="请输入" style="width: 100%" :precision="0"
                                   :controls="false" :min="0" @change="totalAmount()" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="小计" width="100" prop="amount" fixed="right" />
            <el-table-column label="备注" min-width="200" prop="remark" />
          </el-table>
        </div>
      </template>
    </byForm>
  </div>
</template>

<script setup>
import byForm from "@/components/byForm/index";
const route = useRoute();
// 接收父组件的传值
const props = defineProps({
  queryData: Object,
});
const { proxy } = getCurrentInstance();
const frontLinesData = computed(
  () => proxy.useUserStore().allDict["front_lines"]
);
const formData = reactive({
  data: {},
});
const formDom = ref(null);
const judgeStatus = () => {
  if (route.query.processType == 20 || route.query.processType == 10) {
    return true;
  }
  if (props.queryData.recordList && props.queryData.recordList.length > 0) {
    let data = props.queryData.recordList.filter(
      (item) => item.status === 2 && item.nodeType !== 1
    );
    if (data && data.length > 0) {
      return true;
    }
  }
  return false;
};
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  disabled: false,
});
const formConfig = computed(() => {
  return [
    {
      type: "title1",
      title: "商品信息",
      haveLine: true,
    },
    {
      type: "slot",
      slotName: "commodity",
      label: "",
    },
    {
      type: "title1",
      title: "出库总金额",
      haveLine: true,
    },
    {
      type: "input",
      label: "出库总金额",
      prop: "amount",
      itemWidth: 25,
      disabled: true,
    },
  ];
});
const rules = ref({
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
});

const totalAmount = () => {
  let money = 0;
  if (
    formData.data.outboundRecordList &&
    formData.data.outboundRecordList.length > 0
  ) {
    for (let i = 0; i < formData.data.outboundRecordList.length; i++) {
      formData.data.outboundRecordList[i].amount = parseFloat(
        Number(formData.data.outboundRecordList[i].quantity) *
          Number(formData.data.outboundRecordList[i].price)
      ).toFixed(2);
      money = parseFloat(
        Number(money) + Number(formData.data.outboundRecordList[i].amount)
      ).toFixed(2);
    }
  }
  formData.data.amount = money;
};

const handleSubmit = async () => {
  let flag = await formDom.value.handleSubmit(() => {});
  if (flag) {
    if (
      formData.data.outboundRecordList &&
      formData.data.outboundRecordList.length > 0
    ) {
      let total = 0;
      for (let i = 0; i < formData.data.outboundRecordList.length; i++) {
        const ele = formData.data.outboundRecordList[i];
        total += Number(ele.quantity);
        if (
          Number(ele.quantity) + Number(ele.saleOutboundQuantity) >
          Number(ele.orderQuantity)
        ) {
          proxy.msgTip("出库数量加已出库数量不能大于订单数量", 2);
          return false;
        }
      }
      if (!(total > 0)) {
        proxy.msgTip("出库数量不能为0", 2);
        return false;
      }
    }
    return true;
  } else {
    setTimeout(() => {
      const errorDiv = document.getElementsByClassName("is-error");
      errorDiv[0].scrollIntoView();
    }, 0);
  }
  return flag;
};

const getFormData = () => {
  return proxy.deepClone(formData.data);
};
// 向父组件暴露
defineExpose({
  getFormData,
  handleSubmit,
});

const getAllData = (businessId) => {
  let obj = {};
  if (route.query && route.query.obj) {
    obj = JSON.parse(route.query.obj);
  }
  proxy.post("/contract/detail", { id: businessId }).then((res) => {
    formData.data = {
      contractId: businessId,
      outboundRecordList: res.contractProductList.map((x) => ({
        ...x,
        contractProductId: x.id,
        orderQuantity: x.quantity,
        quantity: obj[x.id] || null,
        amount: "",
      })),
      amount: "",
    };
    totalAmount();
    if (
      formData.data.outboundRecordList &&
      formData.data.outboundRecordList.length > 0
    ) {
      let productIds = formData.data.outboundRecordList.map((x) => x.productId);
      proxy.getFileData({
        businessIdList: productIds,
        data: formData.data.outboundRecordList,
        att: "productId",
        businessType: "0",
        fileAtt: "fileList",
        filePathAtt: "fileUrl",
      });
    }
  });
};

onMounted(() => {
  formOption.disabled = judgeStatus();
  if (route.query && route.query.businessId && !route.query.processType) {
    let businessId = route.query.businessId;
    getAllData(businessId);
  } else if (route.query && route.query.businessId && route.query.processType) {
    proxy
      .post("/contractOutboundInfo/detail", { id: route.query.businessId })
      .then((res) => {
        formData.data = res;
        totalAmount();
        if (
          formData.data.outboundRecordList &&
          formData.data.outboundRecordList.length > 0
        ) {
          let productIds = formData.data.outboundRecordList.map(
            (x) => x.productId
          );
          proxy.getFileData({
            businessIdList: productIds,
            data: formData.data.outboundRecordList,
            att: "productId",
            businessType: "0",
            fileAtt: "fileList",
            filePathAtt: "fileUrl",
          });
        }
      });
  }
});
</script>

<style lang="scss" scoped>
.table {
  border-collapse: collapse;
  border-spacing: 0;

  td {
    text-align: center;
    padding: 2px 4px;
    // padding: 5px 10px;
  }
}
.small-title {
  padding-left: 15px;
  margin-bottom: 10px;
  color: #3366ff;
  font-size: 14px;
}
:deep(.el-checkbox) {
  margin-right: 0px;
}
// :deep(.el-collapse-item) {
//   margin-bottom: 10px;
// }
:deep(.el-collapse-item__header) {
  background-color: #eee;
}
</style>