<template>
  <view class="contract-apply-container">
    <view class="page-header">
      <h1>合同申请</h1>
      <button type="button" class="download-btn" @click="download">合同下载</button>
    </view>

    <form class="contract-form">

      <!-- 合同类别 -->
      <view class="form-item">
        <view class="form-label required">合同类别</view>
        <view class="form-input-wrapper">
          <view class="form-select" @click="handleEcTypeClick">
            {{ getEcTypeLabel({ value: formData.ec_type_code }) || formData.ec_type_code || '请选择合同类别' }}
          </view>
          <u-picker :show="showEcTypePicker" :columns="[ecTypeOptions]" keyName="label" @confirm="onEcTypeConfirm"
            @cancel="showEcTypePicker = false" @close="showEcTypePicker = false" :closeOnClickOverlay="true"></u-picker>
        </view>
      </view>

      <!-- 法人/经营者证件类型 -->
      <view class="form-item">
        <view class="form-label required">法人/经营者证件类型</view>
        <view class="form-input-wrapper">
          <view class="form-select" @click="handleCertTypeClick">
            {{ getCertTypeLabel(formData.cert_type) || '请选择证件类型' }}
          </view>
          <u-picker :show="showCertTypePicker" :columns="[certTypeOptions]" keyName="label" @confirm="onCertTypeConfirm"
            @cancel="showCertTypePicker = false" @close="showCertTypePicker = false"
            :closeOnClickOverlay="true"></u-picker>
        </view>
      </view>

      <!-- 法人/经营者姓名 -->
      <view class="form-item">
        <view class="form-label required">法人/经营者姓名</view>
        <input type="text" class="form-input" v-model="formData.cert_name" placeholder="请输入姓名" />
      </view>

      <!-- 法人/经营者证件号码 -->
      <view class="form-item">
        <view class="form-label required">法人/经营者证件号码</view>
        <input type="text" class="form-input" v-model="formData.cert_no" placeholder="请输入证件号码" />
      </view>

      <!-- 签约手机号 -->
      <view class="form-item">
        <view class="form-label required">签约手机号</view>
        <input type="tel" class="form-input" v-model="formData.mobile" placeholder="请输入手机号" />
      </view>

      <!-- 营业执照号 -->
      <view class="form-item">
        <view class="form-label">营业执照号</view>
        <input type="text" class="form-input" v-model="formData.business_license_no" placeholder="请输入营业执照号（可选）" />
      </view>

      <!-- 营业执照名称 -->
      <view class="form-item">
        <view class="form-label">营业执照名称</view>
        <input type="text" class="form-input" v-model="formData.business_license_name" placeholder="请输入营业执照名称（可选）" />
      </view>

      <!-- 企业/经营者结算开户行号 -->
      <view class="form-item">
        <view class="form-label required">企业/经营者结算开户行号</view>
        <input type="text" class="form-input" v-model="formData.openning_bank_code" placeholder="请输入开户行号" />
      </view>

      <!-- 企业/经营者结算开户行名称 -->
      <view class="form-item">
        <view class="form-label required">企业/经营者结算开户行名称</view>
        <input type="text" class="form-input" v-model="formData.openning_bank_name" placeholder="请输入开户行名称" />
      </view>

      <!-- 企业/经营者结算卡性质 -->
      <view class="form-item">
        <view class="form-label required">企业/经营者结算卡性质</view>
        <view class="form-input-wrapper">
          <view class="form-select" @click="handleAcctTypeClick">
            {{ formData.acct_type_code ? (formData.acct_type_code === '57' ? '对公' : '对私') : '请选择结算卡性质' }}
          </view>
          <u-picker :show="showAcctTypePicker" :columns="[acctTypeOptions]" keyName="label" @confirm="onAcctTypeConfirm"
            @cancel="showAcctTypePicker = false" @close="showAcctTypePicker = false"
            :closeOnClickOverlay="true"></u-picker>
        </view>
      </view>

      <!-- 企业/经营者结算卡号 -->
      <view class="form-item">
        <view class="form-label required">企业/经营者结算卡号</view>
        <input type="text" class="form-input" v-model="formData.acct_no" placeholder="请输入结算卡号" />
      </view>

      <!-- 企业/经营者结算卡名称 -->
      <view class="form-item">
        <view class="form-label required">企业/经营者结算卡名称</view>
        <input type="text" class="form-input" v-model="formData.acct_name" placeholder="请输入结算卡名称" />
      </view>

      <!-- 签署协议按钮 -->
      <button type="button" class="sign-btn" @click="goToSignAgreement">签署协议</button>

      <!-- 提交申请按钮 -->
      <view class="bottom-btn">
        <button type="button" class="submit-btn1" @click="ecQuery">结果查询</button>
        <button type="button" class="submit-btn" @click="submitApplication">提交申请</button>
      </view>
    </form>

    <!-- 自定义弹窗 -->
    <view v-if="showCustomModal" class="custom-modal-overlay" @click="closeModal">
      <view class="custom-modal" @click.stop>
        <view class="modal-content">
          <p>查询结果前请先确认是否在以下页面中填写信息</p>
          <view class="link-container">
            <text class="link-text" @click="openApplyUrl">{{ applyUrl || '暂无链接' }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <button type="button" class="confirm-btn2" @click="closeModal">取消</button>
          <button type="button" class="confirm-btn" @click="confirmQuery">确认</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { picUrl, menuButtonInfo, request, NavgateTo, RequsetUrl } from "../../../utils";
import { apiArr } from "../../../api/contract";
export default {
  data() {
    return {
      formData: {
        mch_id: uni.getStorageSync('mchId'),
        ec_type_code: 'Ec007',
        cert_type: '',
        cert_name: '',
        cert_no: '',
        mobile: '',
        business_license_no: '',
        business_license_name: '',
        openning_bank_code: '',
        openning_bank_name: '',
        acct_type_code: '',
        acct_no: '',
        acct_name: '',
        ec_content_parameters: '',
      },
      // picker显示状态
      showEcTypePicker: false,
      showCertTypePicker: false,
      showAcctTypePicker: false,
      // picker选项数据
      ecTypeOptions: [
        { label: '特约商户支付服务合作协议V4.1 + 结算授权委托书', value: 'Ec007' }
      ],
      certTypeOptions: [
        { label: '身份证', value: 'RESIDENT_ID' },
        { label: '护照', value: 'PASSPORT' },
        { label: '港澳居民往来内地通行证', value: 'HK_MACAO_PASS' },
        { label: '台湾居民来往大陆通行证', value: 'TAIWAN_PASS' }
      ],
      acctTypeOptions: [
        { label: '对公', value: '57' },
        { label: '对私', value: '58' }
      ],
      // 自定义弹窗状态
      showCustomModal: false,
      applyUrl: ''
    };
  },
  onLoad(options) {
    // 如果从上一个页面返回并携带了ec_content参数，则设置
    if (options.ec_content) {
      this.formData.ec_content_parameters = options.ec_content;
    }

    // 监听协议签署成功事件
    uni.$on('agreementSigned', (data) => {
      if (data && data.ec_content) {
        this.formData.ec_content_parameters = data.ec_content;
        uni.showToast({
          title: '协议签署成功',
          icon: 'success'
        });
      }
    });
  },

  // 页面卸载时移除事件监听
  onUnload() {
    uni.$off('agreementSigned');
  },
  methods: {
    //下载合同
    download() {
      const storeValue = uni.getStorageSync('storeValue');
      if (!storeValue || !storeValue.ec_apply_id) {
        uni.showToast({
          title: '请先提交申请',
          icon: 'none'
        });
        return;
      }
      const params = {
        ec_apply_id: storeValue.ec_apply_id
      };

      uni.showLoading({
        title: '下载中',
        mask: true
      });

      request(apiArr.ecDownload, "POST", params).then(res => {
        const respData = res.resp_data;
        // 检查合同状态是否为已完成
        if (respData.ec_status === 'COMPLETED' && respData.ec_file) {
          try {
            // 处理Base64编码的文件数据（URL安全的Base64）
            const base64Data = respData.ec_file;
            // 替换URL安全的Base64字符
            const safeBase64 = base64Data.replace(/-/g, '+').replace(/_/g, '/');

            // 文件名（可以根据需要设置）
            const fileName = `contract_${respData.ec_apply_id || Date.now()}.pdf`;

            // 在uni-app中，我们需要使用文件系统API来保存文件
            // 首先获取文件系统管理器
            const fs = uni.getFileSystemManager();

            // 生成临时文件路径
            const tempFilePath = `${uni.env.USER_DATA_PATH}/${fileName}`;

            try {
              // 将Base64数据写入临时文件
              fs.writeFile({
                filePath: tempFilePath,
                data: safeBase64,
                encoding: 'base64',
                success: () => {
                  uni.hideLoading();
                  uni.showToast({
                    title: '合同下载成功',
                    icon: 'success'
                  });
                  console.log('文件保存成功:', tempFilePath);

                  // 打开文件
                  uni.openDocument({
                    filePath: tempFilePath,
                    showMenu: true,
                    success: (openRes) => {
                      console.log('文件打开成功:', openRes);
                    },
                    fail: (openErr) => {
                      console.error('文件打开失败:', openErr);
                      uni.showToast({
                        title: '文件打开失败',
                        icon: 'none'
                      });
                    }
                  });
                },
                fail: (writeErr) => {
                  uni.hideLoading();
                  console.error('文件写入失败:', writeErr);
                  uni.showToast({
                    title: '合同下载失败',
                    icon: 'none'
                  });
                }
              });
            } catch (fsError) {
              uni.hideLoading();
              console.error('文件系统操作失败:', fsError);
              uni.showToast({
                title: '文件系统错误',
                icon: 'none'
              });
            }
          } catch (error) {
            uni.hideLoading();
            console.error('处理文件数据失败:', error);
            uni.showToast({
              title: '文件处理失败',
              icon: 'none'
            });
          }
        } else {
          uni.hideLoading();
          if (respData.ec_status !== 'COMPLETED') {
            uni.showToast({
              title: '电子合同尚未完成',
              icon: 'none'
            });
          } else {
            uni.showToast({
              title: '合同文件不存在',
              icon: 'none'
            });
          }
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('下载合同失败:', err);
        uni.showToast({
          title: '下载失败，请重试',
          icon: 'none'
        });
      })
    },
    // 合同查询
    ecQuery() {
      // 显示自定义弹窗
      this.applyUrl = uni.getStorageSync('applyUrl');
      this.showCustomModal = true;
    },

    // 关闭自定义弹窗
    closeModal() {
      this.showCustomModal = false;
    },

    // 打开申请链接
    openApplyUrl() {
      if (this.applyUrl) {
        uni.navigateTo({
          url: `/pages/webview/webview?url=${encodeURIComponent(this.applyUrl)}`
        });
      }
    },

    // 确认查询
    confirmQuery() {
      this.showCustomModal = false;

      // 继续查询流程
      const storeValue = uni.getStorageSync('storeValue');
      if (!storeValue || !storeValue.ec_apply_id) {
        uni.showToast({
          title: '请先提交申请',
          icon: 'none'
        });
        return;
      }
      const params = {
        ec_apply_id: storeValue.ec_apply_id
      }
      request(apiArr.ecQuery, "POST", params).then(res => {
        if (res.resp_data.ec_status === 'COMPLETED') {
          uni.showToast({
            title: '申请通过',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '申请未通过',
            icon: 'none'
          });
        }
      })
    },

    // 获取合同类别显示文本
    getEcTypeLabel(code) {
      // 兼容直接传入value或者包含value属性的对象
      const targetValue = typeof code === 'string' ? code : (code && code.value ? code.value : code);
      const option = this.ecTypeOptions.find(item => item.value === targetValue);
      return option ? option.label : null;
    },
    // 获取证件类型显示文本
    getCertTypeLabel(type) {
      const option = this.certTypeOptions.find(item => item.value === type);
      return option ? option.label : null;
    },
    // 调试点击事件
    handleEcTypeClick() {
      this.showEcTypePicker = true;
    },
    handleCertTypeClick() {
      this.showCertTypePicker = true;
    },
    handleAcctTypeClick() {
      this.showAcctTypePicker = true;
    },
    // 合同类别选择确认
    onEcTypeConfirm(e) {
      const selectedValue = e.value[0];
      // 查找对应的选项对象
      const selectedOption = this.ecTypeOptions.find(item => item.value === selectedValue);
      this.formData.ec_type_code = selectedOption ? selectedOption.value : selectedValue;
      this.showEcTypePicker = false;
    },
    // 证件类型选择确认
    onCertTypeConfirm(e) {
      const selectedValue = e.value[0];
      const selectedOption = this.certTypeOptions.find(item => item.value === selectedValue.value);
      this.formData.cert_type = selectedOption ? selectedOption.value : selectedValue;
      this.showCertTypePicker = false;
    },
    // 结算卡性质选择确认
    onAcctTypeConfirm(e) {
      const selectedValue = e.value[0];
      const selectedOption = this.acctTypeOptions.find(item => item.value === selectedValue.value);
      this.formData.acct_type_code = selectedOption ? selectedOption.value : selectedValue;
      this.showAcctTypePicker = false;
    },
    goToSignAgreement() {
      NavgateTo('/packages/customerService/contract/index', {
        // 监听协议页面传递回来的数据
        onAgreementSigned: (data) => {
          if (data && data.ec_content) {
            this.formData.ec_content_parameters = data.ec_content;
            uni.showToast({
              title: '协议签署成功',
              icon: 'success'
            });
          }
        }
      });
    },
    submitApplication() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }
      request(apiArr.ecApply, "POST", this.formData).then(res => {
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        });
        uni.setStorageSync('storeValue', { ec_apply_id: res.resp_data.ec_apply_id });
        uni.setStorageSync('applyUrl', res.resp_data.result_url);
      })
    },

    // 表单验证方法
    validateForm() {
      const { formData } = this;

      if (!formData.ec_type_code) {
        uni.showToast({ title: '请选择合同类别', icon: 'none' });
        return false;
      }

      if (!formData.cert_type) {
        uni.showToast({ title: '请选择法人/经营者证件类型', icon: 'none' });
        return false;
      }

      if (!formData.cert_name) {
        uni.showToast({ title: '请输入法人/经营者姓名', icon: 'none' });
        return false;
      }

      if (!formData.cert_no) {
        uni.showToast({ title: '请输入法人/经营者证件号码', icon: 'none' });
        return false;
      }

      // 验证手机号格式
      if (!formData.mobile) {
        uni.showToast({ title: '请输入签约手机号', icon: 'none' });
        return false;
      } else if (!/^1[3-9]\d{9}$/.test(formData.mobile)) {
        uni.showToast({ title: '手机号格式不正确', icon: 'none' });
        return false;
      }

      if (!formData.openning_bank_code) {
        uni.showToast({ title: '请输入企业/经营者结算开户行号', icon: 'none' });
        return false;
      }

      if (!formData.openning_bank_name) {
        uni.showToast({ title: '请输入企业/经营者结算开户行名称', icon: 'none' });
        return false;
      }

      if (!formData.acct_type_code) {
        uni.showToast({ title: '请选择企业/经营者结算卡性质', icon: 'none' });
        return false;
      }

      if (!formData.acct_no) {
        uni.showToast({ title: '请输入企业/经营者结算卡号', icon: 'none' });
        return false;
      }

      if (!formData.acct_name) {
        uni.showToast({ title: '请输入企业/经营者结算卡名称', icon: 'none' });
        return false;
      }

      if (!formData.ec_content_parameters) {
        uni.showToast({ title: '请先点击签署协议并完成协议签署', icon: 'none' });
        return false;
      }

      return true;
    }
  }
};
</script>

<style>
@import url("./index.css");
</style>