<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>
</template>

<script>
import { picUrl, menuButtonInfo, request, NavgateTo, RequsetUrl } from "../../../utils";
import { apiArr } from "../../../api/contract";
export default {
  data() {
    return {
      formData: {
        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' }
      ]
    };
  },
  onLoad(options) {
    // 如果从上一个页面返回并携带了ec_content参数，则设置
    if (options.ec_content) {
      this.formData.ec_content_parameters = options.ec_content;
    }
  },
  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
      });

      // 构建完整的下载URL
      const downloadUrl = `${RequsetUrl}${apiArr.ecDownload}?ec_apply_id=${storeValue.ec_apply_id}`;

      // 调用uni.downloadFile进行文件下载
      uni.downloadFile({
        url: downloadUrl,
        header: {
          'Authorization': uni.getStorageSync('ctoken')
        },
        success: (res) => {
          uni.hideLoading();
          // 下载成功，保存文件到本地
          uni.saveFile({
            tempFilePath: res.tempFilePath,
            success: (saveRes) => {
              uni.showToast({
                title: '下载成功',
                icon: 'success'
              });
              // 提示用户打开文件
              uni.showModal({
                title: '提示',
                content: '合同已下载完成，是否立即打开？',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    // 打开文件
                    uni.openDocument({
                      filePath: saveRes.savedFilePath,
                      showMenu: true,
                      success: (openRes) => {
                        console.log('文件打开成功');
                      },
                      fail: (err) => {
                        console.error('文件打开失败:', err);
                        uni.showToast({
                          title: '文件打开失败',
                          icon: 'none'
                        });
                      }
                    });
                  }
                }
              });
            },
            fail: (err) => {
              console.error('文件保存失败:', err);
              uni.showToast({
                title: '文件保存失败',
                icon: 'none'
              });
            }
          });
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('下载请求失败:', err);
          uni.showToast({
            title: '下载失败，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    // 合同查询
    ecQuery() {
      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() {
      console.log('点击了合同类别，当前状态:', this.showEcTypePicker);
      this.showEcTypePicker = true;
      console.log('设置后状态:', this.showEcTypePicker);
    },
    handleCertTypeClick() {
      console.log('点击了证件类型，当前状态:', this.showCertTypePicker);
      this.showCertTypePicker = true;
      console.log('设置后状态:', this.showCertTypePicker);
    },
    handleAcctTypeClick() {
      console.log('点击了结算卡性质，当前状态:', this.showAcctTypePicker);
      this.showAcctTypePicker = true;
      console.log('设置后状态:', this.showAcctTypePicker);
    },
    // 合同类别选择确认
    onEcTypeConfirm(e) {
      console.log('合同类别确认事件:', e);
      // uview-ui的u-picker组件返回的数据格式
      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) {
      console.log('证件类型确认事件:', 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) {
      console.log('结算卡性质确认事件:', 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;
      }
      // 整合参数并输出到控制台
      console.log('提交的合同申请参数：', this.formData);
      request(apiArr.ecApply, "POST", this.formData).then(res => {
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        });
        // 保存合同申请ID
        uni.setStorageSync('storeValue', { ec_apply_id: res.resp_data.ec_apply_id });
      })
    },

    // 表单验证方法
    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>