<template>
  <div class="form">
    <van-nav-bar
      :title="$t('afterSales.name')"
      :left-text="$t('common.back')"
      left-arrow
      @click-left="onClickLeft"
    >
    </van-nav-bar>
    <testForm
      v-model="formData.data"
      :formOption="formOption"
      :formConfig="formConfig"
      :rules="rules"
      @onSubmit="onSubmit"
      ref="formDom"
    >
      <template #top>
        <div style="width: 100%">
          <ShowFormData :data="formData.data" :config="topConfig">
          </ShowFormData>
        </div>
      </template>

      <template #list>
        <div style="width: 100%">
          <van-collapse v-model="activeNames">
            <van-collapse-item
              v-for="(item, index) in formData.data.bomDetailList"
              :key="item.id"
              :name="item.id"
              :value="'[ ' + item.quantity + ' ]'"
            >
              <template #title>
                <div>
                  <van-icon
                    name="warning-o"
                    v-if="
                      submitData[item.productId].remark &&
                      submitData[item.productId].fileList.length > 0
                    "
                    color="#ee0a24"
                    style="margin-right: 5px"
                  />

                  {{ item.productName }}
                </div>
              </template>
              <div>
                <van-field
                  v-model="submitData[item.productId].remark"
                  label="售后说明"
                  type="textarea"
                  placeholder="请输入"
                  label-align="top"
                  :rules="[{ required: true, message: '请填写售后说明' }]"
                />
                <van-field name="uploader" label="现场照片">
                  <template #input>
                    <van-uploader
                      v-model="submitData[item.productId].fileList"
                      :after-read="afterRead"
                      multiple
                      :max-size="5 * 1024 * 1024"
                      @oversize="onOversize"
                    />
                  </template>
                </van-field>
              </div>
            </van-collapse-item>
          </van-collapse>
          <!-- <div
            v-for="(item, index) in formData.data.bomDetailList"
            :key="index"
          >
            <ShowFormData
              :data="item"
              :config="listConfig"
              :showMore="
                item.afterSalesRecordDetail || route.query.status == 0
                  ? true
                  : false
              "
              @onClickItem="handleClickItem(item)"
            >
            </ShowFormData>
          </div> -->
        </div>
      </template>
    </testForm>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { showSuccessToast, showFailToast } from "vant";
import { useRoute } from "vue-router";
import testForm from "@/components/testForm/index.vue";
import ShowFormData from "@/components/ShowFormData.vue";

const proxy = getCurrentInstance().proxy;
const route = useRoute();
const formDom = ref(null);
const activeNames = ref([]);
const formData = reactive({
  data: {},
});
const rules = {
  customerId: [
    {
      required: true,
      message: proxy.t("afterSales.pleaseSelectTheCustomerName"),
    },
  ],
};
const formOption = reactive({
  readonly: false, //用于控制整个表单是否只读
  disabled: false,
  labelAlign: "top",
  scroll: true,
  labelWidth: "62pk",
  hiddenSubmitBtn: false,
});
const formConfig = reactive([
  {
    type: "slot",
    slotName: "top",
  },
  {
    type: "title",
    title: proxy.t("afterSales.originalPartsList"),
  },
  {
    type: "slot",
    slotName: "list",
  },
  {
    type: "title",
    title: proxy.t("afterSales.programFile"),
  },
  {
    type: "upload",
    label: " ",
    readonly: true,
    prop: "fileList",
  },
]);

const topConfig = ref([
  {
    label: proxy.t("afterSales.afterSalesCode"),
    prop: "code",
  },
  {
    label: proxy.t("afterSales.productName"),
    prop: "productName",
  },
  {
    label: proxy.t("afterSales.productSN"),
    prop: "productSn",
  },
]);

const listConfig = ref([
  {
    label: proxy.t("afterSales.accessoriesName"),
    prop: "productName",
  },
  {
    label: proxy.t("afterSales.quantity"),
    prop: "quantity",
  },
]);

const onClickLeft = () => history.back();
const submitData = ref({});
const getDetails = (id) => {
  proxy.post("/afterSalesRecord/detail", { id }).then((res) => {
    formData.data = res.data;
    const obj = JSON.parse(window.localStorage.getItem("jxstAfterSalesData"));
    for (let i = 0; i < formData.data.bomDetailList.length; i++) {
      const e = formData.data.bomDetailList[i];
      submitData.value[e.productId] = {
        accessoriesId: e.productId,
        remark: "",
        fileList: [],
      };
      // if (e.afterSalesRecordDetail) {
      //   e.productName = e.productName + proxy.t("afterSales.afterSales");
      // }
      // for (const key in obj) {
      //   if (e.productId === key) {
      //     e.accessoriesId = key;
      //     e.remark = obj[key].remark;
      //     e.fileList = obj[key].fileList;
      //   }
      // }
    }
    if (res.data.bomInfoId) {
      proxy
        .post("/fileInfo/getList", { businessIdList: [res.data.bomInfoId] })
        .then((file) => {
          formData.data.fileList = file.data[res.data.bomInfoId].map((x) => ({
            ...x,
            url: x.fileUrl,
          }));
        });
    }
  });
};

onMounted(() => {
  if (route.query.id) {
    getDetails(route.query.id);
    if (route.query.status == 1) {
      formOption.hiddenSubmitBtn = true; //隐藏提交按钮
    }
  }
});

const onSubmit = () => {
  let arr = Object.values(submitData.value);
  for (let i = 0; i < arr.length; i++) {
    const e = arr[i];
    if (e.fileList.length == 0) {
      return showFailToast(`第${i + 1}个配件没传现场照片`);
    }
  }
  proxy
    .post("/afterSalesRecord/afterSales", {
      id: formData.data.id,
      afterSalesRecordDetailList: arr,
    })
    .then(
      () => {
        showSuccessToast(proxy.t("afterSales.operationSuccessful"));
        setTimeout(() => {
          onClickLeft();
        }, 500);
      },
      (err) => {
        return showFailToast(err.message);
      }
    );
};

const handleClickItem = (item) => {
  if (item.afterSalesRecordDetail || route.query.status == 0) {
    proxy.$router.push({
      path: "jxskAfterSalesEditItem",
      query: {
        data: JSON.stringify({
          bomDetailList: [item],
          code: formData.data.code,
          productName: formData.data.productName,
          productSn: formData.data.productSn,
          remark: item.afterSalesRecordDetail
            ? item.afterSalesRecordDetail.remark
            : "",
          fileList: [],
          status: route.query.status,
        }),
      },
    });
  }
};

const afterRead = (file) => {
  if (file && file.length > 0) {
    for (let i = 0; i < file.length; i++) {
      file[i].status = "uploading";
      file[i].message = "上传中...";
      proxy.post("/fileInfo/getSing", { fileName: file[i].file.name }).then(
        (res) => {
          let forms = new FormData();
          forms.append("file", file[i].file);
          proxy
            .post("https://winfaster.obs.cn-south-1.myhuaweicloud.com", {
              ...res.data.uploadBody,
              file: forms.get("file"),
            })
            .then(
              () => {
                file[i].id = res.data.id;
                file[i].url = res.data.fileUrl;
                file[i].fileName = res.data.fileName;
                delete file[i].status;
                delete file[i].message;
              },
              () => {
                file[i].status = "failed";
                file[i].message = "上传失败";
              }
            );
        },
        () => {
          file[i].status = "failed";
          file[i].message = "上传失败";
        }
      );
    }
  } else {
    file.status = "uploading";
    file.message = "上传中...";
    proxy.post("/fileInfo/getSing", { fileName: file.file.name }).then(
      (res) => {
        let forms = new FormData();
        forms.append("file", file.file);
        proxy
          .post("https://winfaster.obs.cn-south-1.myhuaweicloud.com", {
            ...res.data.uploadBody,
            file: forms.get("file"),
          })
          .then(
            () => {
              file.id = res.data.id;
              file.url = res.data.fileUrl;
              file.fileName = res.data.fileName;
              delete file.status;
              delete file.message;
            },
            () => {
              file.status = "failed";
              file.message = "上传失败";
            }
          );
      },
      () => {
        file.status = "failed";
        file.message = "上传失败";
      }
    );
  }
};
// 文件上传
const onOversize = () => {
  showToast("文件大小不能超过 5MB");
};
</script>
<style lang="scss" scoped>
.form {
  margin-bottom: 60px;
}

::v-deep {
  .van-field--label-top .van-icon-arrow {
    right: -2px;
    top: -12px;
  }
  .van-cell__value {
    padding-right: 10px;
  }
}
</style>
