<template>
  <view class="app-container">
    <uv-navbar :title="pageTitle" placeholder autoBack></uv-navbar>

    <view class="review-container" v-if="pageType != 2 && formData.agentAuditStatus != null">
      <view class="review-step u-flex-center">
        <view class="step-title">代理商审核进度：</view>
        <view class="step-tip">
          <text
            :style="formData.agentAuditStatus == 0 ? 'color: #1890ff' : ''"
            >{{ reviewObj[formData.agentAuditStatus] }}</text
          >
        </view>
      </view>
      <view
        class="review-step u-flex-center"
        v-if="formData.agentAuditStatus == 5"
      >
        <view class="step-title">驳回理由：</view>
        <view class="step-tip">
          <text>{{ formData.agentAuditResult }}</text>
        </view>
      </view>

      <template v-if="formData.agentAuditStatus == 10">
        <view class="review-step u-flex-center">
          <view class="step-title">平台审核进度：</view>
          <view class="step-tip">
            <text :style="formData.auditStatus == 0 ? 'color: #1890ff' : ''">{{
              reviewObj[formData.auditStatus]
            }}</text>
          </view>
        </view>
        <view
          class="review-step u-flex-center"
          v-if="formData.auditStatus == 5"
        >
          <view class="step-title">驳回理由：</view>
          <view class="step-tip">
            <text>{{ formData.auditResult }}</text>
          </view>
        </view>
      </template>
    </view>

    <form @submit="nextStep" v-show="step == 1" class="form-container">
      <view class="form-step">
        <view class="step-title">第一步：企业信息</view>
        <view class="step-tip">共三步</view>
      </view>
      <view class="form-list">
        <view class="form-list-title">
          <text>门店关系</text>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>账户码：</view
          >
          <view class="form-value">
            <input
              name="accountCode"
              placeholder="请输入(必填)"
              v-model="formData.accountCode"
              placeholder-style="color: #cccccc"
              :disabled="disabled"
            />
          </view>
        </view>
        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>店铺类型：</view
          >
          <view class="form-value u-mt20">
            <uv-radio-group
              v-model="formData.businessType"
              name="businessType"
              :disabled="disabled"
            >
              <uv-radio
                :name="1"
                label="普通店铺"
                customStyle="margin-right: 20rpx"
              ></uv-radio>
              <uv-radio
                :name="2"
                label="总店商家"
                customStyle="margin-right: 20rpx"
              ></uv-radio>
              <uv-radio :name="3" label="分店商家"></uv-radio>
            </uv-radio-group>
          </view>
        </view>
        <view
          class="form-item u-flex-center-sb"
          v-if="formData.businessType == 3"
        >
          <view class="form-label"
            ><text class="required">*</text>总店邀请：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="parentBusinessCode"
              placeholder="请输入（分店必填）"
              v-model="formData.parentBusinessCode"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>
      </view>

      <view class="form-list">
        <view class="form-list-title">
          <text>企业信息</text>
        </view>
        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>营业执照：</view
          >
          <view class="form-value upload-view">
            <uploadImg
              v-model="formData.businessLicenseImgs"
              :uploadImgCount="1"
              :imgCount="1"
              key="businessLicenseImgs"
              name="businessLicenseImgs"
              @result="resultUrl($event, 1)"
              :type="disabled ? 'view' : 'add'"
            />
            <view class="upload-img-tips">
              *最多上传1张图片（{{ formData.businessLicenseImgs ? 1 : 0 }}/1）
            </view>
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>企业名称：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="enterpriseName"
              placeholder="请输入(必填)"
              v-model="formData.enterpriseName"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>统一信用代码：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="uscCode"
              placeholder="请输入(必填)"
              v-model="formData.uscCode"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>经营范围：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="businessScope"
              placeholder="请输入(必填)"
              v-model="formData.businessScope"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>所属地区：</view
          >
          <view class="form-value" @click="openAreaSelect(1)">
            <!-- <input placeholder="" v-model="formData.region" /> -->
            <text v-if="formData.provinceName">{{
              formData.provinceName + formData.cityName + formData.areaName
            }}</text>
            <text class="placeholder" v-else>请选择(必填)</text>
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>详细地址：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="address"
              placeholder="请输入(必填)"
              v-model="formData.address"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>
      </view>

      <view class="form-list">
        <view class="form-list-title">
          <text>法人信息</text>
        </view>
        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>法人身份证：</view
          >
          <view class="form-value upload-view u-flex-center-sb">
            <view>
              <view class="form-label">身份证正面</view>
              <uploadImg
                v-model="formData.legalIdCardFrontUrl"
                :uploadImgCount="1"
                :imgCount="1"
                key="legalIdCardFrontUrl"
                name="legalIdCardFrontUrl"
                @result="resultUrl($event, 2)"
                :type="disabled ? 'view' : 'add'"
                :imgSize="1"
              />
            </view>
            <view>
              <view class="form-label">身份证反面</view>
              <uploadImg
                v-model="formData.legalIdCardBackUrl"
                :uploadImgCount="1"
                :imgCount="1"
                key="legalIdCardBackUrl"
                name="legalIdCardBackUrl"
                :type="disabled ? 'view' : 'add'"
                :imgSize="1"
              />
            </view>
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label">法人姓名：</view>
          <view class="form-value">
            <text>{{ formData.legalName || "--" }}</text>
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label">身份证号码：</view>
          <view class="form-value">
            <text>{{ formData.legalIdCard || "--" }}</text>
          </view>
        </view>
      </view>

      <view class="form-btn">
        <button class="u-btn-two" form-type="submit">填写店铺信息</button>
      </view>
    </form>

    <!-- 店铺信息 -->
    <form @submit="nextStep2" v-show="step == 2" class="form-container">
      <view class="form-step" v-if="pageType != '2'">
        <view class="step-title">第二步：店铺信息</view>
        <view class="step-tip">共三步</view>
      </view>
      <view class="form-list">
        <view class="form-list-title">
          <text>店铺信息</text>
          <text class="form-title-tips" v-if="pageType != '2'"
            >（审核失败后可修改）</text
          >
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required" v-if="pageType != '2'">*</text>店铺名称<text
              v-if="pageType == '2'"
              style="color: #999999"
              >（不可修改）</text
            >：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled"
              name="businessName"
              placeholder="请输入(必填)"
              v-model="formData.businessName"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>
        <view
          class="form-item u-flex-center-sb"
          @click="goMap"
          v-if="pageType != '2'"
        >
          <view class="form-label"
            ><text class="required">*</text>店铺地图选址：</view
          >
          <view class="form-value">
            <text v-if="formData.latitude && formData.longitude">已选</text>
            <text class="iconfont" v-else>&#xe990;</text>
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label"
            ><text class="required">*</text>客服电话：</view
          >
          <view class="form-value">
            <input
              :disabled="disabled && pageType != '2'"
              name="customerServicePhone"
              placeholder="请输入(必填)"
              v-model="formData.customerServicePhone"
              placeholder-style="color: #cccccc"
              maxlength="11"
              type="number"
            />
          </view>
        </view>
        <view class="form-item u-flex-center-sb">
          <view class="form-label">营业时间：</view>
          <view class="form-value">
            <input
              :disabled="disabled && pageType != '2'"
              name="businessHours"
              placeholder="请输入营业时间"
              v-model="formData.businessHours"
              placeholder-style="color: #cccccc"
            />
          </view>
        </view>
        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>店铺介绍：</view
          >
          <view class="form-value textarea">
            <textarea
              :disabled="disabled && pageType != '2'"
              placeholder="请输入"
              name="description"
              v-model="formData.description"
              placeholder-style="color: #cccccc"
              maxlength="-1"
              auto-height
            />
          </view>
        </view>
      </view>

      <view class="form-list" v-if="pageType != '2'">
        <view class="form-list-title">
          <text>申请材料</text>
        </view>
        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>店招照：</view
          >
          <view class="form-value upload-view">
            <uploadImg
              name="image"
              v-model="formData.image"
              :uploadImgCount="1"
              :imgCount="1"
              key="image"
              :type="disabled ? 'view' : 'add'"
            />
            <view class="upload-img-tips">
              *最多上传1张图片（{{ formData.image ? 1 : 0 }}/1）
            </view>
          </view>
        </view>
        <view class="form-item">
          <view class="form-label"
            ><text class="required">*</text>店内营业场所图：</view
          >
          <view class="form-value upload-view">
            <uploadImg
              name="innerImages"
              v-model="formData.innerImages"
              :uploadImgCount="1"
              :imgCount="2"
              key="innerImages"
              :type="disabled ? 'view' : 'add'"
            />
            <view class="upload-img-tips">
              *最多上传2张图片（{{
                formData.innerImages ? formData.innerImages.length : 0
              }}/2）
            </view>
          </view>
        </view>
      </view>

      <view class="form-btn" v-if="pageType != '2'">
        <view class="u-flex-center-sb">
          <button class="u-btn-two previous-step" @click="previousStep(1)">
            上一步
          </button>
          <button class="u-btn-two" form-type="submit">结算卡信息</button>
        </view>
      </view>
      <view class="form-btn u-flex-center-sb" v-if="pageType == '2'">
        <!-- <button class="u-btn-two previous-step" @click="step = 1">
          上一步
        </button> -->
        <button class="u-btn-two" form-type="submit">保存</button>
      </view>
    </form>

    <!-- 结算卡信息 -->
    <settlementInfo
      v-if="step == 3"
      ref="settlementInfoRef"
      :formData="formData.settlementInfo || {}"
      :disabled="disabled"
      @openAreaSelect="openAreaSelect"
      @formSubmit="formSubmit"
      @setStep="previousStep(2)"
    />

    <!-- 地区选择器 -->
    <uv-picker
      ref="pickerRef"
      :columns="newProvinceDataList"
      keyName="label"
      @confirm="areaConfirm"
      @change="areaChange"
    >
    </uv-picker>

    <!-- 合同确认弹框 -->
    <contractConfirm
      ref="contractConfirmRef"
      :agreementList="agreementList"
      @agreement="handleAgreement"
      @agree="handleAgree"
    />

    <!-- 合同模板 -->
    <contractTemplate ref="contractRef" />
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  cnareaTreeLbs,
  businessApplyApplyInfo,
  businessApplyAdd,
  businessApplyUpdate,
  ocrBusinessLic_Api,
  ocrIdcard_Api,
  businessUpdate_Api,
} from "@/api/index";
import { businessUserInfo_Api } from "@/api/userInfo";
import $config from "@/config/global.config";

const pageTitle = ref("成为商家"); // 页面标题
const pageType = ref("");
const pickerRef = ref(null);
const oldpProvinceDataList = ref([]); // 省市县数据
const newProvinceDataList = ref([]); // 省市县数据

const step = ref(1); // 步骤
// 表单数据
const formData = reactive({
  businessType: 1,
  businessStatus: 1,
});

const disabled = ref(false); // 是否禁用
const settlementInfoRef = ref(null); // 结算卡信息
const contractConfirmRef = ref(null);
const contractRef = ref(null);
const agreementList = ref([
  {
    lable: "软件销售服务三方协议",
    code: "1",
  },
]); // 协议列表

const reviewObj = {
  0: "待审核",
  5: "审核不通过",
  10: "审核通过",
};

// 显示合同
const handleAgreement = (code) => {
  contractRef.value.open(formData);
};

// 第一步确认
const nextStep = () => {
  // console.log("formSubmit=========", formData);
  if (!formData.accountCode) {
    uni.$uv.toast("请输入账户码");
    return false;
  }

  if (!formData.businessType) {
    uni.$uv.toast("请选择店铺类型");
    return false;
  }

  if (formData.businessType == 3 && !formData.parentBusinessCode) {
    uni.$uv.toast("请输入总店邀请");
    return false;
  }

  if (!formData.businessLicenseImgs) {
    uni.$uv.toast("请上传营业执照");
    return false;
  }

  if (!formData.enterpriseName) {
    uni.$uv.toast("请输入企业名称");
    return false;
  }

  if (!formData.uscCode) {
    uni.$uv.toast("请输入统一信用代码");
    return false;
  }

  if (!formData.businessScope) {
    uni.$uv.toast("请输入经营范围");
    return false;
  }

  if (!formData.provinceName) {
    uni.$uv.toast("请选择所属地区");
    return false;
  }

  if (!formData.address) {
    uni.$uv.toast("请输入详细地址");
    return false;
  }

  if (!formData.legalIdCardFrontUrl) {
    uni.$uv.toast("请上传法人身份证正面");
    return false;
  }

  if (!formData.legalIdCardBackUrl) {
    uni.$uv.toast("请上传法人身份证反面");
    return false;
  }

  if (!formData.legalIdCard) {
    uni.$uv.toast("未获取到法人身份证号");
    return false;
  }

  if (!formData.legalName) {
    uni.$uv.toast("未获取到法人姓名");
    return false;
  }

  // console.log("formSubmit", formData);
  step.value = 2;
  uni.pageScrollTo({
    scrollTop: 0, // 滚动到页面的顶部位置
    duration: 300, // 滚动动画的时长，单位ms
  });
  return true;
};

// 第二步确认
const nextStep2 = () => {
  console.log("formSubmit");
  if (!formData.businessName) {
    uni.$uv.toast("请输入店铺名称");
    return false;
  }

  if (!formData.latitude) {
    uni.$uv.toast("请选择店铺地图选址");
    return false;
  }

  if (!formData.customerServicePhone) {
    uni.$uv.toast("请输入客服电话");
    return false;
  }

  if (!$config.telRegex.test(formData.customerServicePhone)) {
    return uni.$uv.toast("请输入正确的联系电话");
  }

  // if (!formData.businessHours) {
  //   uni.$uv.toast("请输入营业时间");
  //   return false;
  // }

  if (!formData.description) {
    uni.$uv.toast("请输入店铺介绍");
    return false;
  }

  if (!formData.image) {
    uni.$uv.toast("请上传店招照");
    return false;
  }
  if (!formData.innerImages || formData.innerImages.length == 0) {
    uni.$uv.toast("请上传店内营业场所图");
    return false;
  }
  if (pageType.value != "2") {
    step.value = 3;
    uni.pageScrollTo({
      scrollTop: 0, // 滚动到页面的顶部位置
      duration: 300, // 滚动动画的时长，单位ms
    });
  } else {
    handleSubmit();
  }
  return true;
};

// 第三步确认
const formSubmit = (form) => {
  // console.log("form", form);
  Object.assign(formData, {
    settlementInfo: form,
  });
  // console.log("formSubmit", formData);
  // return;
  contractConfirmRef.value.open();
  return true;
};

const previousStep = (val) => {
  step.value = val;
  uni.pageScrollTo({
    scrollTop: 0, // 滚动到页面的顶部位置
    duration: 300, // 滚动动画的时长，单位ms
  });
};

// 同意协议
const handleAgree = () => {
  // if (formData.signImage) {
  //   handleSubmit();
  //   return;
  // }
  uni.navigateTo({
    url: "/pages/agencyCenter/signature",
    events: {
      confirm: (e) => {
        // console.log(e.data);
        formData.signImage = e.data;
        if (!e.data) {
          return uni.$uv.toast("手写签名获取失败，请重新绘制");
        }
        setTimeout(() => {
          handleSubmit();
        }, 500);
      },
    },
  });
};

const handleSubmit = () => {
  // console.log("handleSubmit");
  let form = {
    ...formData,
    businessLicenseImgs: [formData.businessLicenseImgs],
    auditStatus: 0,
  };
  // console.log("form===>", form);
  // return
  let url = formData.businessId ? businessApplyUpdate : businessApplyAdd;
  if (pageType.value == "2") {
    url = businessUpdate_Api;
  }
  url(form).then(async (res) => {
    if (res && res.code == 200) {
      uni.showToast({
        title: "提交成功",
        icon: "none",
        duration: 3000,
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    } else {
      uni.$uv.toast(res.msg);
    }
  });
};

// 地区选择器触发
const areaChange = (e) => {
  const { columnIndex, index, indexs } = e;
  // 改变了省
  if (columnIndex === 0) {
    newProvinceDataList.value[1] =
      oldpProvinceDataList.value[index].children || [];
    newProvinceDataList.value[2] =
      oldpProvinceDataList.value[index].children[0]?.children || [];
    pickerRef.value.setIndexs([index, 0, 0], true);
  } else if (columnIndex === 1) {
    newProvinceDataList.value[2] =
      newProvinceDataList.value[1][index].children || [];
    pickerRef.value.setIndexs(indexs, true);
  }
};
const areaSelectType = ref(1);
// 选择地址
const openAreaSelect = (type) => {
  if (disabled.value) return;
  areaSelectType.value = type;
  pickerRef.value.open();
};

// 获取地区
const areaConfirm = (e) => {
  if (e.value.length > 0) {
    if (areaSelectType.value == 1) {
      formData.provinceName = e.value[0].label;
      formData.provinceCode = e.value[0].value;
      formData.cityName = e.value[1].label;
      formData.cityCode = e.value[1].value;
      formData.areaName = e.value[2].label;
      formData.areaCode = e.value[2].value;
    } else {
      settlementInfoRef.value.updateForm({
        bankProvinceName: e.value[0].label,
        bankProvinceCode: e.value[0].value,
        bankCityName: e.value[1].label,
        bankCityCode: e.value[1].value,
        bankAreaName: e.value[2].label,
        bankAreaCode: e.value[2].value,
      });
    }
  }
};

const getUserInfo = (type) => {
  disabled.value = true;
  let url = type == "2" ? businessUserInfo_Api : businessApplyApplyInfo;
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });
  //获取店铺信息
  url()
    .then((res) => {
      uni.hideLoading();
      if (res && res.code == 200 && res.data) {
        res.data.businessLicenseImgs = res.data.businessLicenseImgs.toString();
        Object.assign(formData, res.data);
        if (res.data.agentAuditStatus == 5 || res.data.auditStatus == 5) {
          disabled.value = false;
        }
      } else {
        if (pageType.value == 2) {
          uni.$uv.toast("未获取到信息");
          setTimeout(() => {
            uni.navigateBack();
          }, 500);
        }
        disabled.value = false;
      }
    })
    .catch((err) => {
      console.log(err);
      uni.hideLoading();
      uni.$uv.toast("未获取到信息");
      setTimeout(() => {
        uni.navigateBack();
      }, 500);
    });
};

//跳转到地图
const goMap = () => {
  if (disabled.value) return;
  uni.chooseLocation({
    success: (res) => {
      if (res.address) {
        // formData.address = res.address;
        formData.latitude = res.latitude;
        formData.longitude = res.longitude;
        // showSelected.value = true;
      } else {
        // showSelected.value = false;
      }
    },
    fail: (fail) => {
      console.log(fail);
    },
  });
};

// 上传图片结果
const resultUrl = (e, type) => {
  console.log(e, type);
  // return;
  if (e && e.length > 0) {
    let url = type == 1 ? ocrBusinessLic_Api : ocrIdcard_Api;
    url({ imgHttpUrl: e[e.length - 1], front: 1 }).then((res) => {
      console.log(res);

      if (res && res.code == 200) {
        if (type == 1 && res.data) {
          formData.enterpriseName = res.data.name;
          formData.address = res.data.address;
          formData.uscCode = res.data.creditCode;
        } else if (type == 2) {
          if (res.data) {
            formData.legalName = res.data.name;
            formData.legalIdCard = res.data.idNo;
            if(!res.data.name || !res.data.idNo) {
              uni.$uv.toast("未获取到法人姓名或身份证号，请重新上传");
            }
          } else {
            uni.$uv.toast("身份证识别失败，请检查后重新上传");
          }
        }
      }
    });
  }
};

onLoad((options) => {
  if (options.type) {
    if (options.type == "2") {
      pageTitle.value = "门店档案";
      step.value = 2;
    }
    pageType.value = options.type;
  }
  getUserInfo(options.type);
  //获取省市区
  cnareaTreeLbs().then(async (res) => {
    if (res.code == 200) {
      let provincesList = res.data.children;
      // console.log(provincesList);
      newProvinceDataList.value = [
        provincesList,
        provincesList[0].children,
        provincesList[0].children[0].children,
      ];
      oldpProvinceDataList.value = provincesList;
    }
  });
});
</script>

<style lang="scss" scoped>
.app-container {
  box-sizing: border-box;
  background: #f7f7f7;
  min-height: 100vh;
  // padding-bottom: 20rpx;
  .u-btn-two.previous-step {
    background: #ffffff;
    color: #999999;
    border: 1rpx solid #999999; /* Changed from border: 1rpx solid #e5e5e5; */
    margin-right: 40rpx;
  }
  .review-container {
    background: #ffffff;
    color: #000000;
    padding: 20rpx 30rpx 10rpx 30rpx;
    border-bottom: 1rpx solid #e5e5e5;
    font-size: 28rpx;
    .review-step {
      margin-bottom: 10rpx;
      .step-title {
        flex-shrink: 0;
      }
    }
  }
}
</style>
