<template>
  <!-- 商户信息添加|修改 -->
  <div class="merchantSetPage flex-col">
    <s-header :name="$t('merchantManage.merchantInformation')" :noback="false"></s-header>
    <div class="merchantSetBox">
      <van-tabs v-model:active="active">
        <van-tab :title="$t('merchantManage.essentialInformation')">
          <van-form @submit="onSubmit">
            <div class="van-cell van-field">
              <div class="van-cell__title van-field__label"><span>{{ $t('merchantManage.accountNumber') }}</span>
              </div>
              <div class="van-field__value o-pt-8" style="text-align: left;">
                <span> {{ adminObj.username }}</span>
              </div>
            </div>
            <van-field v-model="relationObj.relationUsername" name="password"
              :label="$t('merchantManage.relationAdmin')"
              :placeholder="$t('merchantManage.relationAdminPlaceholder')" />
            <van-field v-model="adminObj.name" name="password" :label="$t('merchantManage.fullNameLabel')"
              :placeholder="$t('merchantManage.fullNamePlaceholder')"
              :rules="[{ required: true, message: $t('merchantManage.fullNamePlaceholder') }]" />
            <van-field v-model="adminObj.password" name="password" type="password" clearable
              :label="$t('merchantManage.passwordLabel')" :placeholder="$t('merchantManage.passwordPlaceholder')" />
            <span class="txt">{{ $t('merchantManage.leavBlanToIndiNoModi') }}</span>
            <van-field v-model="adminObj.checkPassword" name="password" type="password" clearable
              :label="$t('merchantManage.confirmPasswordLabel')"
              :placeholder="$t('merchantManage.confirmPasswordPlaceholder')" />
            <van-field v-model="adminObj.email" name="password" :label="$t('merchantManage.mailbox')"
              :placeholder="$t('merchantManage.mailboxPlaceholder')" />
            <van-field v-model="adminObj.phone" name="password" :label="$t('merchantManage.telephone')"
              :placeholder="$t('merchantManage.telephonePlaceholder')" />
            <van-field v-model="adminObj.tradeMerchantNo" name="password"
              :label="$t('merchantManage.merchantFilingNumberLabel')"
              :placeholder="$t('merchantManage.merchantFilingNumberPlaceholder')" />
            <div class="van-cell van-field">
              <div class="van-cell__title van-field__label"><span>{{ $t('merchantManage.domesticOrNot') }}:</span>
              </div>
              <div class="van-cell__value van-field__value radioBox">
                <van-radio-group v-model="adminObj.ifForeign" direction="horizontal">
                  <van-radio name="0" icon-size="18px">{{ $t('merchantManage.yes') }}</van-radio>
                  <van-radio name="1" icon-size="18px">{{ $t('merchantManage.no') }}</van-radio>
                </van-radio-group>
              </div>
            </div>
            <div v-if="adminType === 0 || adminType === 1">
              <div class="van-cell van-field">
                <div class="van-cell__title van-field__label"><span>{{ $t('merchantManage.discountCode') }}</span>
                </div>
                <div class="van-cell__value van-field__value radioBox">
                  <van-radio-group v-model="adminObj.promoCodeOpen" direction="horizontal">
                    <van-radio name="0" icon-size="18px">{{ $t('merchantManage.yes') }}</van-radio>
                    <van-radio name="1" icon-size="18px">{{ $t('merchantManage.no') }}</van-radio>
                  </van-radio-group>
                </div>
              </div>
              <div class="van-cell van-field">
                <div class="van-cell__title van-field__label"><span>{{ $t('merchantManage.paymentPlatform')
                    }}</span>
                </div>
                <div class="van-cell__value van-field__value radioBox">
                  <van-radio-group v-model="adminObj.payPlatform" direction="horizontal">
                    <van-radio name="0" icon-size="18px">{{ $t('merchantManage.convergence') }}</van-radio>
                    <van-radio name="1" icon-size="18px">{{ $t('merchantManage.huifuPaymnt') }}</van-radio>
                  </van-radio-group>
                </div>
              </div>
              <div class="van-cell van-field">
                <div class="van-cell__title van-field__label"><span>{{ $t('merchantManage.isDistribution')
                    }}</span>
                </div>
                <div class="van-cell__value van-field__value radioBox">
                  <van-radio-group v-model="adminObj.isDistribution" direction="horizontal">
                    <van-radio name="0" icon-size="18px">{{ $t('merchantManage.hidden') }}</van-radio>
                    <van-radio name="1" icon-size="18px">{{ $t('merchantManage.reveal') }}</van-radio>
                  </van-radio-group>
                </div>
              </div>
            </div>
            <van-row justify="space-around" style="padding: 10px; margin: 20px 0;">
              <van-button span="5" round type="primary" style="height: 2em; padding: 0 2em;" native-type="submit">{{
      $t('merchantManage.modificationSubmission') }}
              </van-button>
            </van-row>
          </van-form>
        </van-tab>
        <van-tab :title="$t('merchantManage.withdrawalData')" class="tab">
          <div class="kBordBott o-w o-pb-10">
            <span class="info">{{ $t('merchantManage.merchantType') }}：{{ adminMchObj.altMerchantType == 10 ?
      "个人" :
      (adminMchObj.altMerchantType == 12 ? "企业" : "") }}</span>
            <span class="info">{{ $t('merchantManage.contactName') }}：{{ adminMchObj.busiContactName }}</span>
            <span class="info">{{ $t('merchantManage.cellPhone') }}：{{ adminMchObj.busiContactMobileNo }}</span>
          </div>
          <div class="kBordBott o-w o-pb-10">

            <span class="info">{{ $t('merchantManage.nameOfLegalPerson/Individual') }}：{{ adminMchObj.legalPerson
              }}</span>
            <span class="info">{{ $t('merchantManage.phoneNumberOfLegalPerson/Individual') }}：{{
      adminMchObj.phoneNo
    }}</span>
            <span class="info">{{ $t('merchantManage.legalPerson/IndividualIDNumber') }}：{{ adminMchObj.idCardNo
              }}</span>
            <span class="info">{{ $t('merchantManage.validityOfIDCard') }}：{{ adminMchObj.idCardExpiry }}</span>
            <span v-if="adminMchObj.altMerchantType == 12" class="info">{{
      $t('merchantManage.businessLicenseCode')
    }}：{{ adminMchObj.licenseNo }}</span>
            <span v-if="adminMchObj.altMerchantType == 12" class="info">{{
      $t('merchantManage.validityOfBusinessLicense') }}：{{ adminMchObj.licenseExpiry
              }}</span>
            <span class="info">{{ $t('merchantManage.natureOfBusiness') }}：{{ adminMchObj.manageScope }}</span>
            <span class="info">{{ $t('merchantManage.businessAddress') }}：{{ adminMchObj.manageAddr }}</span>
          </div>

          <div class="kBordBott">
            <span class="info">{{ $t('merchantManage.accountType') }}
              ：{{ adminMchObj.bankAccountType === 1 ? $t('merchantManage.debitCard') :
      (adminMchObj.bankAccountType
        ===
        4
        ? $t('merchantManage.corporateAccount') : "") }}</span>
            <span class="info">{{ $t('merchantManage.bankAccountName') }}：{{ adminMchObj.bankAccountName }}</span>
            <span class="info">{{ $t('merchantManage.bankAccount') }}：{{ adminMchObj.bankAccountNo }}</span>
            <span v-if="adminMchObj.bankAccountType == 4" class="info">{{ $t('merchantManage.bankNo') }}：{{
      adminMchObj.bankChannelNo }}</span>
          </div>
          <div v-if="adminType < 2">
            <span class="info">{{ $t('merchantManage.joinpayMch') }}：{{ joinpayState }}</span>
            <span class="info">{{ $t('merchantManage.huifuMch') }}：{{ huifuState }}</span>
          </div>
        </van-tab>
        <van-tab :title="$t('merchantManage.sqbConfig')" class="tab">
          <div v-if="sqbConfig" class="kBordBott o-w o-pb-10">
            <span class="info">{{ $t('merchantManage.deviceId') }}：{{ sqbConfig.deviceId }}</span>
            <span class="info">{{ $t('merchantManage.terminalSn') }}：{{ sqbConfig.terminalSn }}</span>
            <span class="info">{{ $t('merchantManage.check') }}：{{ sqbConfig.checkin == '1' ?
      $t('merchantManage.checkIn') : $t('merchantManage.checkOut') }}</span>
          </div>
          <div v-else>
            <div class="activate o-pt-20">
              <van-cell-group inset>
                <van-field label-align="center" v-model="activateCode" :label="$t('merchantManage.activateCode')" :placeholder="$t('merchantManage.activateCodePlaceholder')" />
              </van-cell-group>
            </div>
            <van-row justify="space-around" style=" margin: 20px 0;">
              <van-button span="5" round type="primary" style="height: 30px; padding: 0 30px;" @click="activeConfig">{{
                $t('merchantManage.activate') }}
              </van-button>
            </van-row>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>
<script>
import { onMounted, ref } from "vue";
import sHeader from "@/components/SimpleHeader";
import { getAdmin, getRelation, getAdminMch, updateAdmin, getHuifuMch, getRelationAdminId, getSqbConfigApi, activeSqbConfigApi } from "@/service/merchantManage";
import { showConfirmDialog, showFailToast, showSuccessToast, showToast } from "vant";
import { useRoute } from "vue-router";
import { getLoginUser, styleUrl } from "@/common/js/utils";
import { useI18n } from "vue-i18n";

export default {
  components: { sHeader },
  setup() {
    // 引入语言
    const { t } = useI18n();
    const active = ref(0);
    const tabType = ref('0');
    const user = getLoginUser();
    const adminType = ref(user.type);
    const route = useRoute();
    const merchantId = ref('');
    const adminObj = ref({});
    const relationObj = ref({});
    const adminMchObj = ref({});
    const huifuMchObj = ref({});
    const ifForeign = ref('0');
    const huifuState = ref('未入驻');
    const joinpayState = ref('未入驻');
    // 收钱吧配置
    const sqbConfig = ref();
    // 激活码
    const activateCode = ref('');

    onMounted(async () => {
      // 加载样式
      styleUrl('merchantManage');
      merchantId.value = route.query.merchantId;
      getAdminFun();
      getRelationFun();
      getAdminMchFun();
      getHuifuMchFun();
      getSqbConfig();

    });
    const getAdminFun = async () => {
      const { data } = await getAdmin({ id: merchantId.value });
      if (data.code === "00000") {
        adminObj.value = data.data;
        adminObj.value.password = '';
        adminObj.value.checkPassword = '';
        if (data.data.payPlatform == null) {
          adminObj.value.payPlatform = '0';
        }
        if (data.data.promoCodeOpen == null) {
          adminObj.value.promoCodeOpen = '1';
        }
        ifForeign.value = data.data.ifForeign;
      }
    };
    const getRelationFun = async () => {
      const { data } = await getRelation({ adminId: merchantId.value });
      if (data.code === "00000") {
        if (data.data != null) {
          relationObj.value = data.data;
          relationObj.value.relationUsername = data.data.username;
        }
      }
    }
    const getAdminMchFun = async () => {
      const { data } = await getAdminMch({ id: merchantId.value });
      if (data.code === "00000") {
        if (data.data != null) {
          adminMchObj.value = data.data;
          if (adminMchObj.value.approveStatus == '审核通过') {
            if (adminMchObj.value.signStatus == '签约成功') {
              joinpayState.value = adminMchObj.value.signStatus;
            } else {
              if (adminMchObj.value.approveNote != null && adminMchObj.value.approveNote != '') {
                joinpayState.value = adminMchObj.value.approveNote;
              }
            }
          } else {
            if (adminMchObj.value.approveNote != null && adminMchObj.value.approveNote != '') {
              joinpayState.value = adminMchObj.value.approveNote;
            }
          }
        }
      }
    }
    const getHuifuMchFun = async () => {
      const { data } = await getHuifuMch({ adminId: merchantId.value });
      if (data.code === "00000") {
        if (data.data != null) {
          huifuMchObj.value = data.data;
          if (huifuMchObj.value.status == '2') {
            huifuState.value = '签约成功';
          } else {
            if (huifuMchObj.value.auditDesc != null && huifuMchObj.value.auditDesc != '') {
              huifuState.value = huifuMchObj.value.auditDesc;
            }
          }

        }
      }
    }

    // 获取收钱吧配置
    const getSqbConfig = async () => {
      const { data } = await getSqbConfigApi({ adminId: merchantId.value });
      if (data.code === "00000") {
        if (data.data != null) {
          sqbConfig.value = data.data;
          console.log("sqbConfig", sqbConfig.value);
        }
      }
    };
    const onSubmit = async () => {
      try {
        if (relationObj.value.relationUsername != null) {
          const result = await getRelationAdminId({ relationUsername: relationObj.value.relationUsername });
          if (result.data.code === "00000") {
            if (result.data.data != null) {
              adminObj.value.relationAdminId = result.data.data;
            }
          }
        }
        const params = {
          id: adminObj.value.id,
          name: adminObj.value.name,
          username: adminObj.value.username,
          relationAdminId: adminObj.value.relationAdminId,
          ifForeign: adminObj.value.ifForeign,
          phone: adminObj.value.phone,
          email: adminObj.value.email,
          tradeMerchantNo: adminObj.value.tradeMerchantNo,
        };
        console.log('adminObj', adminObj.value);
        if (adminType.value === 0 || adminType.value === 1) {
          params.promoCodeOpen = adminObj.value.promoCodeOpen;
          params.applyStartTime = adminObj.value.applyStartTime;
          params.applyEndTime = adminObj.value.applyEndTime;
          params.payPlatform = adminObj.value.payPlatform;
          params.isDistribution = adminObj.value.isDistribution;
        }
        if (adminObj.value.password !== '') {
          if (adminObj.value.checkPassword === '') { showFailToast(t('merchantManage.confirmPasswordPlaceholder')); return; }
          if (adminObj.value.password === adminObj.value.checkPassword) {
            params.password = adminObj.value.password;
          } else {
            showFailToast(t('merchantManage.theTwoPasswordsAreDifferent'));
          }
        }
        console.log('params', params);
        const { data } = await updateAdmin(params);
        if (data.code === "00000") {
          showSuccessToast(t('merchantManage.modificationSucceeded'));
          setTimeout(() => {
            getAdminFun();
          }, 1500);
        } else { showFailToast(data.message); }
        console.log('onSubmit', data);
      } catch (error) {
        // 如果上面的方法执行失败，会执行到这里
        console.error('提交管理员信息失败', error);
      }
    }

    // 激活收钱吧配置
    const activeConfig = () => {
      if (activateCode.value == null || activateCode.value == '') {
        showToast(t('merchantManage.activateCodePlaceholder'));
        return;
      }
      showConfirmDialog({
        title: t('merchantManage.tips'),
        message: t('merchantManage.isActivate'),
      }).then(async() => {
        const { data } = await activeSqbConfigApi({adminId: merchantId.value, code: activateCode.value});
        if (data.data != null) {
          showSuccessToast(t('merchantManage.activateSucceeded'));
        } else {
          showFailToast(t('merchantManage.activateFailed'));
        }
      }).catch((error) => {
        console.error(error);
      })
    }
    return {
      tabType,
      adminType,
      adminObj,
      relationObj,
      adminMchObj,
      huifuMchObj,
      onSubmit,
      joinpayState,
      huifuState,
      active,
      sqbConfig,
      activeConfig,
      activateCode,
    };
  },
};
</script>
<style lang="less" scoped>
@import "../../common/style/common.less";
@import "../../styles/merchantManage/index.less";
</style>
