<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 #file>
        <div style="width: 100%;">
          <div v-if="
            formData.data.fileList && formData.data.fileList.length > 0
          ">
            <span v-for="item in formData.data.fileList" :key="item.id" @click="onPreviewFile(item)"
                  style="margin-right: 10px; cursor: pointer; color: #409eff">
              {{ item.name }}
            </span>
          </div>
          <div v-else>无</div>
        </div>
      </template>

      <template #fileOne>
        <div style="width: 100%">
          <van-uploader v-model="formData.data.fileListOne" multiple :show-upload="false" />
        </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].quantity &&
                      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].quantity" label="售后数量" type="digit" placeholder="请输入" label-align="top" />
                <van-field v-model="submitData[item.productId].remark" label="售后说明" type="textarea" placeholder="请输入" label-align="top" />
                <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, watch } 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: {
    fileListOne: [],
    fileList: [],
  },
});
const rules = {
  afterSalesRemark: [
    {
      required: true,
      message: "请输入其他问题",
    },
  ],
  amount: [
    {
      required: true,
      message: "请输入售后金额",
    },
  ],
};
const formOption = reactive({
  readonly: false, //用于控制整个表单是否只读
  disabled: false,
  labelAlign: "top",
  scroll: true,
  labelWidth: "62pk",
  hiddenSubmitBtn: false,
});
const formConfig = reactive([
  {
    type: "slot",
    slotName: "top",
  },
  {
    type: "slot",
    label: "售后附件",
    slotName: "fileOne",
  },
  // {
  //   type: "upload",
  //   label: "售后附件",
  //   readonly: true,
  //   showUpload: false,
  //   prop: "fileListOne",
  // },
  {
    type: "title",
    title: "配件问题",
  },
  {
    type: "slot",
    slotName: "list",
  },
  {
    type: "title",
    title: "其他问题",
  },
  {
    type: "input",
    itemType: "textarea",
    label: "",
    prop: "afterSalesRemark",
  },
  {
    type: "title",
    title: "售后金额",
  },
  {
    type: "input",
    itemType: "number",
    label: "",
    prop: "amount",
    clearable: true,
  },
  {
    type: "title",
    title: proxy.t("afterSales.programFile"),
  },
  // {
  //   type: "upload",
  //   label: " ",
  //   readonly: true,
  //   showUpload: false,
  //   prop: "fileList",
  // },
  {
    type: "slot",
    slotName: "file",
  },
]);

const topConfig = ref([
  {
    label: proxy.t("afterSales.afterSalesCode"),
    prop: "code",
  },
  {
    label: proxy.t("afterSales.productSN"),
    prop: "productSn",
  },
  {
    label: proxy.t("afterSales.productName"),
    prop: "productName",
  },
  {
    label: "规格型号",
    prop: "productSpec",
  },
  {
    label: "售后类型",
    prop: "typeName",
  },
  {
    label: "售后说明",
    prop: "remark",
  },
  {
    label: "客户联系人",
    prop: "contactName",
  },
  {
    label: "客户联系方式",
    prop: "contactInfo",
  },
  {
    label: "售后人员",
    prop: "afterSalesPersonIdName",
  },
]);

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 afterSalesType = ref([]);
const userList = ref([]);

const getDetails = async (id) => {
  const data1 = await proxy.getDictOne(["after_sales_type"]);
  afterSalesType.value = data1["after_sales_type"].data.map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));

  const data2 = await proxy.get("/system/user/list?pageNum=1&pageSize=9999");
  userList.value = data2.rows.map((item) => {
    return {
      label: item.userName,
      value: item.userId,
    };
  });

  const status = route.query.status;
  proxy.post("/afterSalesRecord/detail", { id }).then(async (res) => {
    if (status == 0) {
      for (let i = 0; i < res.data.bomDetailList.length; i++) {
        const e = res.data.bomDetailList[i];
        submitData.value[e.productId] = {
          accessoriesId: e.productId,
          productName: e.productName,
          quantity: null,
          remark: "",
          fileList: [],
        };
      }
      formData.data = res.data;
    } else {
      let arr = res.data.bomDetailList.map((x) => x.afterSalesRecordDetail.id);
      for (let i = 0; i < res.data.bomDetailList.length; i++) {
        const e = res.data.bomDetailList[i];
        submitData.value[e.productId] = {
          accessoriesId: e.productId,
          productName: e.productName,
          quantity: e.afterSalesRecordDetail.quantity,
          remark: e.afterSalesRecordDetail.remark,
          fileList: [],
        };
      }
      formData.data = res.data;
      const fileObj = await proxy.post("/fileInfo/getList", {
        businessIdList: arr,
      });
      for (let i = 0; i < res.data.bomDetailList.length; i++) {
        const e = res.data.bomDetailList[i];
        for (const key in fileObj.data) {
          if (e.afterSalesRecordDetail.id == key) {
            submitData.value[e.productId].fileList = fileObj.data[key].map(
              (item) => ({
                raw: item,
                name: item.fileName,
                url: item.fileUrl,
              })
            );
          }
        }
      }
    }

    proxy
      .post("/fileInfo/getList", {
        businessIdList: [id],
      })
      .then((fileObj) => {
        if (fileObj.data && fileObj.data[id]) {
          formData.data.fileListOne = fileObj.data[id].map((x) => ({
            raw: x,
            name: x.fileName,
            url: x.fileUrl,
          }));
          console.log(formData.data.fileListOne, "asda");
        }
      });

    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,
            name: x.fileName,
            url: x.fileUrl,
          }));
        });
    }

    let typeName = afterSalesType.value.find((x) => x.value == res.data.type);
    if (typeName) {
      formData.data.typeName = typeName.label;
    }
    let userName = userList.value.find(
      (x) => x.value == res.data.afterSalesPersonId
    );
    if (userName) {
      formData.data.afterSalesPersonIdName = userName.label;
    }
  });
};

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

const onSubmit = () => {
  let arr = Object.values(submitData.value);
  for (let i = 0; i < arr.length; i++) {
    const e = arr[i];
    if (e.quantity || e.remark.trim() || e.fileList.length > 0) {
      if (!e.quantity) {
        return showFailToast(`请填写${e.productName}配件的售后数量`);
      }
      if (!e.remark.trim()) {
        return showFailToast(`请填写${e.productName}配件的售后说明`);
      }
      if (e.fileList.length == 0) {
        return showFailToast(`请上传${e.productName}配件的现场照片`);
      }
    }
  }

  if (!(Number(formData.data.amount) > 0)) {
    return showFailToast(`售后金额需大于0`);
  }
  proxy
    .post("/afterSalesRecord/afterSales", {
      id: formData.data.id,
      afterSalesRemark: formData.data.afterSalesRemark,
      amount: formData.data.amount,
      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");
};

watch(
  () => formData.data.fileList,
  (val) => {
    console.log(val, "a");
  }
);

const onPreviewFile = (item) => {
  uni.postMessage({
    data: {
      type: "file",
      url: item.url,
      name: item.name,
    },
  });
};
</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>
