<template>
  <div class="row mt14">
    <el-form label-width="150" label-position="left" v-loading="loading">
      <el-form-item label="信息来源" v-if="isHeadShop != 1">
        <el-radio-group :model-value="typeValue" @change="typeValueChange">
          <el-radio label="进件信息" :value="route.query.shopId"></el-radio>
          <el-radio label="复用主店信息" :value="route.query.mainId" v-if="mainInfo && mainInfo.shopId"></el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="!form.shopId">
        <el-form-item label-width="0">
          <el-text>您还未申请进件</el-text>
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" @click="toApplyment">去申请</el-button>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="商户号">
          <el-text>{{ form.merchantCode }}</el-text>
        </el-form-item>
        <el-form-item label="商户类型">
          <el-text>{{ userTypeListFilter(form.userType).label }}</el-text>
        </el-form-item>
        <el-form-item label="支付宝进件状态">
          <div class="column">
            <div>
              <el-text :type="statusListFilter(form.alipayStatus).type">
                {{ statusListFilter(form.alipayStatus).label }}
              </el-text>
            </div>
            <div class="center" v-if="form.alipayStatus == 'SIGN'">
              <el-text>待签约</el-text>
              <el-link type="primary" @click="singCodeDialogRef?.show(form.alipaySignUrl, 1)">查看签约码</el-link>
            </div>
            <div class="error_text" v-if="form.alipayStatus == 'REJECTED'">
              失败原因：{{ form.alipayErrorMsg }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="微信进件状态">
          <div class="column">
            <div>
              <el-text :type="statusListFilter(form.wechatStatus).type">
                {{ statusListFilter(form.wechatStatus).label }}
              </el-text>
            </div>
            <div class="center" v-if="form.wechatStatus == 'SIGN'">
              <el-text>待签约</el-text>
              <el-link type="primary" @click="singCodeDialogRef?.show(form.wechatSignUrl, 2)">查看签约码</el-link>
            </div>
            <div class="error_text" v-if="form.wechatStatus == 'REJECTED'">
              失败原因：{{ form.wechatErrorMsg }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="最后提交时间">
          <el-text>{{ form.updateTime }}</el-text>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-text>{{ form.createTime }}</el-text>
        </el-form-item>
        <el-form-item v-if="typeValue == shopId">
          <el-button link type="primary"
            v-if="form.wechatStatus == 'INIT' || form.wechatStatus == 'AUDIT' || form.wechatStatus == 'SIGN' || form.alipayStatus == 'INIT' || form.alipayStatus == 'AUDIT' || form.alipayStatus == 'SIGN'"
            @click="checkStatusHandle()">查询</el-button>
          <el-button type="primary" @click="toDetail('check')">查看详情</el-button>
          <el-button type="primary" @click="toDetail('editor')"
            v-if="form.alipayStatus == 'REJECTED' || form.wechatStatus == 'REJECTED'">修改</el-button>
        </el-form-item>
      </template>
    </el-form>
    <singCodeDialog ref="singCodeDialogRef" />
    <!-- 分店复用主店信息弹窗 -->
    <el-dialog title="注意" width="400px" top="40vh" v-model="mainDialogVisable">
      <span>是否复用主店？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="toApplymentRouter">自己申请</el-button>
          <el-button type="primary" @click="shopMerchantPutAjax" :loading="mainDialogVisableLoading">复用主店信息</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { shopMerchantGet, getMainMerchant, shopMerchantPut, entryManagerDetail, queryEntry } from '@/api/common'
import singCodeDialog from '@/views/applyments/components/singCodeDialog.vue';

const singCodeDialogRef = ref(null)
const route = useRoute()
const router = useRouter()
const shopId = ref(route.query.shopId)
const userTypeList = ref([
  {
    value: '0',
    label: '个体商户'
  },
  {
    value: '1',
    label: '企业商户'
  },
])
function userTypeListFilter(userType) {
  let obj = userTypeList.value.find(item => item.value == userType)
  if (obj) {
    return obj
  } else {
    return {
      label: userType,
      value: userType
    }
  }
}
const statusList = ref([
  {
    value: 'WAIT',
    label: '待提交',
    type: 'info'
  },
  {
    value: 'INIT',
    label: '待处理',
    type: 'info'
  },
  {
    value: 'AUDIT',
    label: '待审核',
    type: 'warning'
  },
  {
    value: 'SIGN',
    label: '待签约',
    type: 'primary'
  },
  {
    value: 'FINISH',
    label: '已完成',
    type: 'success'
  },
  {
    value: 'REJECTED',
    label: '失败',
    type: 'danger'
  },
])
function statusListFilter(status) {
  let obj = statusList.value.find(item => item.value == status)
  if (obj) {
    return obj
  } else {
    return {
      label: status,
      value: status
    }
  }
}
const loading = ref(false)
const form = ref({})


// 查询状态
async function checkStatusHandle() {
  try {
    loading.value = true
    const businessLicenceInfo = form.value.businessLicenceInfo
    await queryEntry({
      shopId: form.value.shopId,
      licenceNo: businessLicenceInfo.licenceNo
    })
    updateData()
  } catch (error) {
    loading.value = false
    console.log(error);
  }
}

// 获取主店进件信息
const mainInfo = ref({})
async function headShopApplmentInfo() {
  try {
    if (route.query.mainId) {
      const res = await getMainMerchant({
        shopId: route.query.mainId
      })
      mainInfo.value = res
    }
  } catch (error) {
    console.log(error);
  }
}

// 跳转进件逻辑处理
const mainDialogVisable = ref(false)
const mainDialogVisableLoading = ref(false)
const isHeadShop = ref(route.query.isHeadShop)
async function toApplyment() {
  let shopType = route.query.shopType
  if (shopType == 'chain' || shopType == 'join') {
    if (isHeadShop == 1) {
      toApplymentRouter()
    } else {
      // 分店弹窗选择
      await headShopApplmentInfo()
      if (mainInfo.value && mainInfo.value.shopId) {
        mainDialogVisable.value = true
      } else {
        toApplymentRouter()
      }
    }
  } else {
    toApplymentRouter()
  }
}

// 跳转进件
function toApplymentRouter() {
  router.push({ name: 'applyment_in', query: { shopId: shopId.value } });
}

// 复用主店的进件信息
async function shopMerchantPutAjax() {
  try {
    mainDialogVisableLoading.value = true
    await shopMerchantPut({
      shopId: shopId.value,
      relatedId: mainInfo.value.shopId,
      nativeMerchantDTO: {
        wechatMerchantId: mainInfo.value.wechatMerchantId,
        alipayMerchantId: mainInfo.value.alipayMerchantId,
        alipayAuthInfo: mainInfo.value.alipayAuthInfo
      }
    })
    ElNotification({
      title: '注意',
      message: '复用成功',
      type: 'success'
    })
    mainDialogVisable.value = false
    updateData()
  } catch (error) {
    console.log(error);
  }
  mainDialogVisableLoading.value = false
}

// 跳转编辑页面
function toDetail(type) {
  const businessLicenceInfo = form.value.businessLicenceInfo
  router.push({
    name: 'applyment_in',
    query: {
      shopId: shopId.value,
      licenceNo: businessLicenceInfo.licenceNo,
      type: type
    }
  })
}

// 切换进件类型
const typeValue = ref('')
async function typeValueChange(e) {
  await ElMessageBox.confirm('确定要切换进件类型吗？', '注意').then(async () => {
    try {
      try {
        loading.value = true
        await shopMerchantPut({
          shopId: shopId.value,
          relatedId: e,
        })
        typeValue.value = e
        updateData()
      } catch (error) {
        console.log(error)
        loading.value = false
      }
    } catch (error) {
      console.log(error);
    }
  }).catch(() => { })
}

// 刷新进件数据
async function updateData() {
  try {
    loading.value = true
    const res = await shopMerchantGet({
      shopId: shopId.value
    })

    if (res && res.shopDirectMerchant) {
      form.value = res.shopDirectMerchant
      typeValue.value = res.relatedId
    } else {
      typeValue.value = shopId.value
      const applymentRes = await entryManagerDetail({ shopId: shopId.value })
      if (applymentRes && applymentRes.shopId) {
        form.value = applymentRes
      } else {
        form.value = ''
      }
    }
  } catch (error) {
    console.log(error);
  }
  loading.value = false
}

onMounted(() => {
  updateData()
  headShopApplmentInfo()
})
</script>

<style scoped lang="scss">
.row {
  &.mt14 {
    margin-top: 14px;
  }
}

.center {
  display: flex;
  gap: 14px;
  align-items: center;
}

.column {
  display: flex;
  flex-direction: column;
}

.error_text {
  font-size: 14px;
  color: #999;
}
</style>