<template>
  <view>
    <image
      class="bg-image"
      mode="widthFix"
      src="https://qtzl.etcjz.cn/default-bucket/20240324/3eba2095f5204798a1f8101b_beijing.jpg"
    ></image>
    <view class="content-re">
      <custom-header title="用户信息"></custom-header>
      <view v-if="isShow">
        <formBuilderVue
          :formData="formData"
          :config="config"
          @radioChange="radioChange"
          @submit="submit"
          @uploadImgOcr="uploadImg"
        ></formBuilderVue>
      </view>
    </view>
    <agreementfrom />
  </view>
</template>

<script setup lang='ts'>
import CustomHeader from "@/components/CustomHeader";
import formBuilderVue from "@/components/form-builder/form-builder-vue3";
import { TypeData, Index } from "@/components/form-builder/tools";
import agreementfrom from "./components/agreement";
import { ref, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { requestNew, request } from "@/utils/network/request";
import fromData from "./fromData";
import ocrHandle from "./ocrHandle";
import {
  setToken,
  setItem,
  getToken,
  getItem,
  StorageKeys,
} from "@/utils/storage";
// import { useQdOrderStore } from "@/stores/qdOrder.js";
import { storeToRefs } from "pinia";
// import {
// 	userInfoFormData
// } from '@/utils/formDataHandle'
let config = ref<any>({
  hasReturn: "false",
  submitName: "下一步",
  titleWidth: 180,
  isHeader: true,
});
let formData = ref<any>(fromData);
let formDataList = ref([]);
const isShow = ref(true);
const orderNo = ref("");

// const qdOrderStore = useQdOrderStore();
// const { qdOrderVal, cusQdOrderVal } = storeToRefs(qdOrderStore);

//获取页面配置
onLoad((opin) => {
  // 只调用trackEvent接口
  orderNo.value = opin.orderNo;
  const params = {
    orderNo: orderNo.value,
  };
  trackEvent(params);
});

function trackEvent(params) {
  requestNew("/iaw/h5/order/web/queryOrder", {
    data: params,
  }).then((res) => {
    // 根据orderStepCode判断跳转逻辑
    if (res.data.orderStepCode === 1) {
      // orderStepCode为1时继续执行后续操作
      if (res.data.userType === "PERSONAL_USER") {
        // 个人办理
        danChange(false);
      } else {
        // 单位办理
        danChange(true);
      }
      handleMobile(res.data); //处理联系方式
      handleAgentTel(res.data); //处理经办人电话
      nextTick(() => {});
    } else if (res.data.orderStepCode === 2) {
      // orderStepCode为2时跳转到drivingLicense页面
      uni.navigateTo({
        url: `/pages/drivingLicense/drivingLicense?orderNo=${orderNo.value}`,
        animationType: "pop-in",
        animationDuration: 500,
      });
      return;
    } else {
      // 其他情况跳转到payment页面
      uni.navigateTo({
        url: `/pages/payment/payment?orderNo=${orderNo.value}`,
        animationType: "pop-in",
        animationDuration: 500,
      });
      return;
    }
  });
}


function handleMobile(data) {
  const itemData = formData.value[Index("联系方式", formData.value)];
  if (data.customerTel) {
    itemData[itemData.value] = data.customerTel || "";
    itemData.disabled = true;
  }
}
function handleAgentTel(data) {
  const itemData = formData.value[Index("经办人电话", formData.value)];
  if (data.customerTel) {
    itemData[itemData.value] = data.customerTel || "";
    itemData.disabled = true;
  }
}
//初始判断单位办理还是个人办理
function danChange(key) {
  if (key) {
    submitCode = "20";
    // 单位办理
    businesses(false);
    handleDan(false);
    formData.value[Index("部门名称", formData.value)].department = "本部";
  } else {
    submitCode = "22";
    // 个人办理
    businesses(true);
    handleDan(true);
  }
}
//单项选择器
function radioChange(e: any, item: TypeData, opin) {
  if (item.title === "本人办理") {
    if (e.detail.value === "1") {
      businesses(true);
    } else {
      businesses(false);
    }
  }
}
//本人办理还是他人办理 ,true为本人办理
function businesses(key: Boolean) {
  formData.value[Index("委托书", formData.value)].show = key;
  formData.value[Index("本人办理", formData.value)].underline = key;
  formData.value[Index("经办人姓名", formData.value)].show = key;
  formData.value[Index("经办人证件号码", formData.value)].show = key;
  formData.value[Index("经办人电话", formData.value)].show = key;
  // formData.value[Index("经办人证件识别信息如下", formData.value)].show = key;
  formData.value[Index("经办人证件人像面", formData.value)].show = key;
  formData.value[Index("经办人证件国徽面", formData.value)].show = key;
}
// 个人办理还是单位办理 true为个人办理
function handleDan(key) {
  formData.value[Index("营业执照", formData.value)].show = key;
  formData.value[Index("委托书", formData.value)].show = key;
  formData.value[Index("公司名称", formData.value)].show = key;
  formData.value[Index("部门名称", formData.value)].show = key;
  formData.value[Index("社会信用代码", formData.value)].show = key;
  // formData.value[Index('住址', formData.value)].show = !key
  formData.value[Index("本人办理", formData.value)].show = !key;
  formData.value[Index("人像面", formData.value)].show = !key;
  formData.value[Index("国徽面", formData.value)].show = !key;
  formData.value[Index("证件号码", formData.value)].show = !key;
  // formData.value[Index('住址', formData.value)].show = !key
  formData.value[Index("姓名", formData.value)].show = !key;
  formData.value[Index("联系方式", formData.value)].show = !key;
}

// 提交个人信息接口
let submitCode = "22";
// ocr图片处理和额外请求参数处理
const { uploadImgHandle, submitQuery } = ocrHandle();

function uploadImg(fileList, item) {
  uploadImgHandle(fileList, item, formData);
}
async function submit(item: any) {
  try {
    if (isLock.value) return;
    isLock.value = true;
    let data = {
      ...submitQuery.value,
    };
    // 处理参数，为空的不携带
    for (const key in item) {
      if (item[key] || item[key] === 0 || item[key] === false) {
        data[key] = item[key];
      }
    }
    console.log(data, "isAgent之前");

    const openIdKey = await register(data);
	
	//之前加密请求方式，暂时弃用（注释），后面删除
    // if (!openIdKey) {
    //   return;
    // }
    // let { jumpPage } = config.value;
    // data.userAddress = data.userAddress || data.address;

    // let options = {
    //   type: 2,
    //   data: data,
    //   method: "POST",
    //   showLoading: true,
    // };
    // console.log(options, "请求参数");
    // await request("ISSUES_ORDER_USERUPLOAD", options).then((res) => {
    //   console.log(res, "res");
    //   if (res.statusCode === 0) {
    //     uni.navigateTo({
    //       url: "/" + jumpPage + `?qdOrderNo=${qdOrderVal.value.orderNo}`,
    //       animationType: "pop-in",
    //       animationDuration: 500,
    //     });
    //   }
    // });
  } catch (e) {
    //TODO handle the exception
  } finally {
    isLock.value = false;
  }
}
let isLock = ref(false);
// 用户信息提交上传
function register(data: any) {
  console.log(data, "datasjsjsjsjsj");
  let params: any = {};
  params.agentAddress = data.agentAddress;
  params.agentIdNum = data.agentIdNum;
  params.agentIdType = data.agentIdType;
  params.agentIdVld = data.agentIdVld;
  params.agentName = data.agentName;
  params.agentNegImgUrl = data.agentNegImgUrl;
  params.agentPosImgUrl = data.agentPosImgUrl;
  params.agentTel = data.agentTel;
  params.customerId = data.customerId;
  params.customerIdVld = data.customerIdVld;
  params.department = data.department;
  // params.loginSource = data.loginSource;
  params.loginSource = "431bfdc8b9c645e0b293b85d6ce1948n";
  params.mobile = data.tel;
  params.orderNo = orderNo.value;
  params.proxyUrl = data.proxyUrl;
  params.userAddress = data.address;
  params.userIdNum = data.userIdNum;
  params.userIdType = data.userIdType;
  params.userName = data.userName;
  params.userNegImgUrl = data.userIdNeImageUrl;
  params.userPosImgUrl = data.userIdPoImageUrl;

  if (data.isSelf === "0" || submitCode === "20") {
    // 他人办理
    params.agentIdNum = data.agentIdNum;
    params.agentIdType = data.agentIdType;
    params.agentName = data.agentName;
  }
  if (submitCode === "20") {
    // 单位办理
    params.userType = "ENTERPRISE";
    params.department = data.department;
    params.businessLicenseUrl = data.businessLicenseUrl; // 添加营业执照图片地址
  } else {
    params.userType = "PERSONAL";
  }
  console.log(params, "params", submitCode);
  console.log(orderNo.value, "fanhui");

  return requestNew("/iaw/h5/order/web/upUser", {
    data: params,
  }).then((res) => {
    if (res.code === 0) {
      let data = res.data;
      // 保存token
      setToken(data.accessToken);
      setItem(StorageKeys.OpenId, data.openId);
      uni.navigateTo({
        url: `/pages/drivingLicense/drivingLicense?orderNo=${orderNo.value}`,
        animationType: "pop-in",
        animationDuration: 500,
      });
      // return data.openId;
    } else {
      return false;
    }
  });
}
</script>
<style lang='scss' scoped>
</style>