<template>
  <div class="bg-white dark:!bg-[#060818]">
    <el-tabs type="border-card" class="bg-gray-100 dark:bg-[#060818]">
      <el-tab-pane :label="$t('companyDetails')" class="custom-tab-pane">
        <el-form :model="companyForm" :rules="stockRules" ref="companyFormRef" label-width="210px">
          <el-row>
            <el-col :span="24" :md="6">
              <el-form-item :label="$t('currentPack')+':'" prop="company_package_id">
                <el-select v-model="companyForm.company_package_id" clearable placeholder="请选择套餐">
                  <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="5">
              <el-form-item :label="$t('end_use_time')+':'" prop="name">
                {{ companyForm.end_use_time }}
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="5">
              <el-form-item :label="$t('user_num')+':'" prop="name">
                {{ companyForm.user_num }}
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('companyName')+':'" prop="name">
                <el-input v-model="companyForm.name" :minlength="2" :maxlength="20" disabled clearable placeholder="请输入公司名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('credit_code')+':'" prop="credit_code">
                <el-input v-model="companyForm.credit_code" :minlength="2" :maxlength="20" disabled clearable placeholder="请输入统一社会信用代码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('industry')+':'" prop="industry">
                <el-input v-model="companyForm.industry" :minlength="2" :maxlength="20" disabled clearable placeholder="请输入行业"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('company_user_name')+':'" prop="user_name">
                <el-input v-model="companyForm.user_name" :minlength="2" :maxlength="20" disabled clearable placeholder="请输入联系人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('companyPhone')+':'" prop="phone">
                <el-input v-model="companyForm.phone" :minlength="2" :maxlength="20" disabled clearable placeholder="请输入联系人电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('companyEmail')+':'" prop="email">
                <el-input v-model="companyForm.email" :minlength="2" :maxlength="20" disabled clearable placeholder="请输入邮箱"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('postalCode')+':'" prop="postal_code">
                <el-input v-model="companyForm.postal_code" :minlength="2" :maxlength="20" disabled clearable placeholder="请输入邮箱"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('website')+':'" prop="website">
                <el-input v-model="companyForm.website" :minlength="2" :maxlength="20" disabled clearable placeholder="请输入官网地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('companyAddress')+':'" prop="">
                <el-cascader class="w-full" size="default" :options="options" disabled clearable v-model="selectedOptions"></el-cascader>
                <span>
                  <el-input class="!w-full mt-3" v-model="companyForm.address" disabled placeholder="请输入"></el-input>
                </span>
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="10">
              <el-form-item :label="$t('companyLicense')+':'" prop="license">
                <el-upload
                  disabled
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="companyForm.license" :src="companyForm.license" class="avatar w-28 h-28" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="flex justify-center"><el-button type="primary" @click="submitWarehouseForm">{{$t('save')}}</el-button></div>
      </el-tab-pane>
      <el-tab-pane :label="$t('info')" class="custom-tab-pane">
        <el-form :model="infoForm" :rules="stockRules" ref="infoFormRef" label-width="140px">
          <el-row>
            <el-col :span="24" :md="12" :lg="8">
              <el-form-item :label="$t('nickname')+':'" prop="nickname">
                {{ infoForm.nickname }}
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="12" :lg="8">
              <el-form-item :label="$t('loginName')+':'" prop="username">
                {{ infoForm.username }}
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="12" :lg="8">
              <el-form-item :label="$t('phone')+':'" prop="phone">
                {{ infoForm.phone }}
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="12" :lg="8">
              <el-form-item :label="$t('companyEmail')+':'" prop="email">
                {{ infoForm.email }}
              </el-form-item>
            </el-col>
            <el-col :span="24" :md="12" :lg="8">
              <el-form-item :label="$t('profile')+':'" prop="face">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :show-file-list="false"
                  :on-success="handleInfoSuccess"
                  :before-upload="beforeInfoUpload"
                >
                  <img v-if="infoForm.face" :src="infoForm.face" class="avatar w-28 h-28" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div class="flex justify-center">
          <el-button type="primary" @click="paySubmit">支付测试</el-button>
          <el-button type="primary" @click="bindWeChat">{{$t('bindWeChat')}}</el-button
          ><!-- v-if="infoForm.openid && infoForm.openid==''" -->
          <el-button type="primary" @click="submitInfo">{{$t('save')}}</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="$t('bindWeChat')" v-model="dialogVisibleWeChat" width="30%" center @close="addHandleCancle" class="!rounded-lg">
      <div class="flex justify-center">
        <qrcode-vue :value="qrCodeValue" :size="200" level="H"></qrcode-vue>
      </div>
    </el-dialog>
  </div>
</template>
  
<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';
import * as API_Company from '@/api/company';
import * as API_Package from '@/api/package';
import * as API_Auth from '@/api/auth';
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';
import { ElMessageBox, FormInstance, ElMessage } from 'element-plus';
import type { UploadProps } from 'element-plus';
import { useStore } from 'vuex';
import { submit } from '@/api/goodsInventoryLoss';
import axios from 'axios';
import QrcodeVue from 'qrcode.vue';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
/* declare const WeixinJSBridge: {
  invoke(api: string, config: any, callback: (res: any) => void): void;
}; */
/* import QRCode from 'qrcodejs2'; */
const store = useStore();
const tableData = ref<any>({});

const uploadUrl = ref(import.meta.env.VITE_API_URL + '/uploaders');
const companyForm = ref<any>({
  role_id: '',
  name: '',
  money: '',
  day: '',
  use_able: false,
  remark: '',
  address: '',
  license: '',
  company_package_id: '',
});
const stockRules = ref();
const options = ref<any[]>(regionData);
const selectedOptions = ref<any[]>([]);
const loading = ref(false);

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  companyForm.value.license = response.url; //URL.createObjectURL(uploadFile.raw!);
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!');
    return false;
  }
  return true;
};
/* 支付 */
let ip = ref<any>(''); // 添加 ip 属性
const payForm = ref<any>({
  id: store.state.user.user.company_vo.id,
  pay_type: 'wx',
  ip: ip.value,
  user_id: store.state.user.user.uid,
});
const paySubmit = () => {
  API_Auth.getPayUrl(payForm.value).then((res) => {
    console.log(res);
    callWeChatPay(res);
  });
};

// 调用微信支付
const callWeChatPay = (payParams: any) => {
  // 确保WeixinJSBridge对象可用
  if (typeof WeixinJSBridge == 'undefined') {
    const onBridgeReadyWrapper = () => onBridgeReady(payParams); // 创建一个包装函数
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReadyWrapper, false);
    } else if ((document as any).attachEvent) {
      (document as any).attachEvent('WeixinJSBridgeReady', onBridgeReadyWrapper);
      (document as any).attachEvent('onWeixinJSBridgeReady', onBridgeReadyWrapper);
    }
  } else {
    onBridgeReady(payParams);
  }
};

// 微信支付桥接准备就绪
const onBridgeReady = (payParams: any) => {
  WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    {
      appId: payParams.appId,
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType,
      paySign: payParams.paySign,
    },
    (res: any) => {
      if (res.err_msg == 'get_brand_wcpay_request:ok') {
        // 支付成功
        ElMessage.success(t('pay_success'));
        // 可以在这里添加支付成功后的逻辑，比如刷新订单状态
      } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
        // 支付取消
        ElMessage.info(t('pay_info'));
      } else {
        // 支付失败
        ElMessage.error(t('pay_error'));
      }
    }
  );
};

/* 打开绑定微信 */
const dialogVisibleWeChat = ref(false);
const qrCodeValue = ref('');
const addHandleCancle = () => {
  dialogVisibleWeChat.value = false;
};

/* 获取当前ip */

const getIPAddress = async () => {
  try {
    const response = await axios.get('https://api.ipify.org?format=json');
    ip.value = response.data.ip;
  } catch (error) {
    console.error('Error fetching IP address:', error);
    ip.value = 'Unable to fetch IP';
  }
};
/* 绑定微信 */
const bindWeChat = () => {
  API_Auth.getOpenIdCode(store.state.user.user.uid, { ip: ip.value })
    .then((res) => {
      dialogVisibleWeChat.value = true;
      qrCodeValue.value = res;
    })
    .catch((error) => {
      console.error('Error getting OpenID code:', error);
      ElMessage.error(t('bindWeChatError'));
    });
};

/* 个人信息详情 */
const handleInfoSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  infoForm.value.face = response.url; //URL.createObjectURL(uploadFile.raw!);
};

const beforeInfoUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!');
    return false;
  }
  return true;
};
const adminName = (val: string[]) => {
  let text = '';
  console.log(val);
  if (val !== undefined) {
    text += codeToText[val[0]];
    text += codeToText[val[1]];
    text += codeToText[val[2]];
  }
  return text;
};
const companyFormRef = ref();
const submitWarehouseForm = () => {
  companyFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const params = { ...companyForm.value };
      params.province = selectedOptions.value.join(',');
      API_Company.editCompany(companyForm.value.id, params).then(() => {
        ElMessage.success(t('edit_success')+'!');
        GET_CompanyList();
      });
    } else {
      ElMessage.error(t('form_erroe')+'!');
      /*    store.dispatch('showMessage', { message: '表单填写有误，请核对！', type: 'error' }); */
      return false;
    }
  });
};

const GET_CompanyList = () => {
  loading.value = true;
  API_Company.getOne(store.state.user.user.company_vo.id)
    .then((response) => {
      loading.value = false;
      selectedOptions.value = response.province.split(',');
      /*  response.records.map((el: any) => {
        if (el.province !== undefined) {
          el.license = el.license.replace('blob:', '');
          el.province = el.province.split(',');
        }
        return el;
      }); */
      companyForm.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};
const packageList = ref<any>([]);
const GET_PackageList = () => {
  API_Package.packageList({ page_no: 1, page_size: 1000, use_able: true }).then((res) => {
    packageList.value = res.records;
  });
};
/* 获取当前登录人详情 */
const infoForm = ref<any>({
  face: '',
});
let imgUrl = ref<any>('');
const GET_Info = () => {
  API_Auth.getAdministratorDetail(store.state.user.user.uid).then((res) => {
    infoForm.value = res;
    imgUrl.value = res.face;
    console.log(res);
  });
};
const submitInfo = () => {
  if (infoForm.value.face == undefined) {
    return ElMessage.error(t('uploadPro')+'!');
  } else if (infoForm.value.face == imgUrl.value) {
    return ElMessage.error(t('uploadNewPro')+'!');
  }
  API_Auth.editAdministrator(store.state.user.user.uid, { face: infoForm.value.face }).then((res) => {
    ElMessage.success(t('edit_success')+'!');
    GET_Info();
    store.dispatch('updateUserAction', res);
    /*     location.reload(); */
  });
};

onMounted(() => {
  GET_CompanyList();
  GET_PackageList();
  GET_Info();
  getIPAddress();
});
</script>
  
  <style scoped >
.container {
  background-color: #fff;
  padding: 10px;
  position: relative;
}

.site-tag {
  margin: 0 3px;
}

.site-new-tag-input {
  width: 100px;
}

:deep(.site-logo .el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  /* &:hover {
    border-color: #409eff;
  } */
}

.logo-uploader-icon {
  font-size: 20px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.site-logo-img {
  width: 120px;
  height: 120px;
  display: block;
}

.image-pane .el-input-group {
  width: 200px;
}

.point-pane .el-input-group {
  width: 200px;
}
.custom-tabs {
  @apply dark:bg-[#060818];
}

:deep(.el-tabs__header) {
  @apply dark:bg-[#060818];
}

:deep(.custom-tab-pane) {
  @apply dark:bg-[#060818];
}
:deep(.el-tabs__item.is-active) {
  @apply dark:bg-[#060818]; /* 替换为你想要的 Tailwind CSS 背景色类 */
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 112px;
  height: 112px;
  text-align: center;
}
</style>