<template>
  <page-header-wrapper>
    <!-- 列表页 -->
    <a-card v-show="!vdata.currentApplyPage.component" class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
        <!-- 时间搜索控件 -->
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker
            ref="dateRangePicker"
            v-model:value="vdata.searchData['queryDateRange']"
            customDateRangeType="date"
          />
        </a-form-item>
        <!--				<jeepay-text-up v-model:value="vdata.searchData['unionSearchId']" :placeholder="'申请单号/进件商户名'" />-->
        <jeepay-text-up  v-model:value="vdata.searchData['mchApplyName']"  :placeholder="'商户号/商户名称'"  />
        <jeepay-text-up  v-model:value="vdata.searchData['ifName']"   :placeholder="'支付通道'"  />
        <jeepay-text-up   v-model:value="vdata.searchData['isvNo']"  :placeholder="'渠道名称/渠道号'"  />
        <jeepay-text-up  v-model:value="vdata.searchData['autoConfigMchAppId']" :placeholder="'应用名称/应用ID'" />
        <a-form-item label="" class="table-search-item">
          <a-select  v-model:value="vdata.searchData.range"  placeholder="应用类型"  >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">线下场景</a-select-option>
            <a-select-option value="1">线上场景</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="" class="table-search-item">
          <a-select  v-model:value="vdata.searchData.merchantType"  placeholder="商户类型" >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="1">小微</a-select-option>
            <a-select-option value="2">个体</a-select-option>
            <a-select-option value="3">企业</a-select-option>
          </a-select>
        </a-form-item>

        <JeepaySelect   ref="stateRef"   placeholder="进件状态"  :value="vdata.searchData.state"  >
          <a-select   v-model:value="vdata.searchData.state"  @change="stateRef.textupHandle()" >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">草稿</a-select-option>
            <a-select-option value="1">审核中</a-select-option>
            <a-select-option value="2">进件成功</a-select-option>
            <a-select-option value="3">驳回待修改</a-select-option>
            <a-select-option value="4">待验证</a-select-option>
            <a-select-option value="5">待签约</a-select-option>
            <a-select-option value="12">待通道复审</a-select-option>
            <a-select-option value="7">等待预审</a-select-option>
            <a-select-option value="8">预审拒绝</a-select-option>
            <a-select-option value="20">已风控</a-select-option>
            <a-select-option value="21">已冻结</a-select-option>
            <a-select-option value="100">进件请求中</a-select-option>
          </a-select>
        </JeepaySelect>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        row-key="applyId"
      >
        <!-- 表格顶部按钮行插槽 -->
        <template #topBtnSlot>
          <!--					<a-button v-if="$access('ENT_MCH_APPLYMENT_ADD')" type="primary"-->
          <!--						@click="addFunc('')"><plus-outlined />发起进件</a-button>-->
          <a-button
            v-if="$access('ENT_MCH_APPLYMENT_ADD')"
            type="primary"
            @click="getVisibleAdd()"
            ><plus-outlined />发起进件</a-button
          >
        </template>

        <!-- body 渲染插槽 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'state'">
            <a-badge v-if="record.state == 0" status="default" text="草稿" />
            <a-badge
              v-if="record.state == 1"
              status="warning"
              text="等待审核结果"
            />
            <a-badge
              v-if="record.state == 2"
              status="success"
              text="进件成功"
            />
            <a-badge
              v-if="record.state == 3"
              status="error"
              text="驳回待修改"
            />
            <a-badge
              v-if="record.state == 4"
              status="processing"
              text="待验证"
            />
            <a-badge @click="nextBizsDrawerRef.show(record.applyId)"
              v-if="record.state == 5"
              status="processing"
              text="待签约"
            />
            <a-badge
              v-if="record.state == 7"
              status="processing"
              text="等待预审"
            />
            <a-badge
              v-if="record.state == 8"
              status="error"
              text="预审拒绝"
            />
            <a-badge v-if="record.state == 20" status="error" text="已风控" />
            <a-badge v-if="record.state == 21" status="error" text="已冻结" />
            <a-badge
              v-if="record.state == 100"
              status="warning"
              text="进件请求中"
            />
            <a-badge
                v-if="record.state == 12"
                status="warning"
                text="待通道复审"
            />
            <link-outlined v-if="record.state == 5"  @click="nextBizsDrawerRef.show(record.applyId)"  style="font-size: 16px; padding-left: 5px;color: #1965FF" />

            <a-tooltip  v-if="record.applyErrorInfo && record.state == 3 || record.state == 8 " :title="record.applyErrorInfo">
              <info-circle-outlined style="font-size: 16px; padding-left: 5px;color: #FF0000"/>
            </a-tooltip>
            <a-tooltip  v-if="record.ifCode == 'kqpay' && record.state == 12" title="快钱通道营业执照商户支持先开通后审核，复审期间的交易会在人工审批完成后结算，复审时间一般为1个工作日。">
              <info-circle-outlined style="font-size: 16px; padding-left: 5px;color: #FF0000"/>
            </a-tooltip>

            <QrcodeOutlined v-if=" (record.state == 4) && (record.ifCode === 'wxpay' || record.ifCode === 'sftpay') "  style="font-size: 16px; margin-left: 10px"  @click="showQrImgFunc(record)" />

            <reload-outlined
              @click="queryChannelState(record.applyId, record.state)"
              style="color: #1890ff; margin-left: 10px"
              v-if="(record.state == 1 || record.state == 4 || record.state == 7  || record.state == 5  ||  record.state == 12)   && $access('ENT_MCH_APPLYMENT_GET_INFO') " />
          </template>

          <template v-if="column.key === 'type'">
            <a-tag :color="record.type === 1 ? 'green' : 'orange'">
              {{ record.type === 1 ? "普通商户" : "特约商户" }}
            </a-tag>
          </template>

          <template v-if="column.key === 'autoConfigMchAppId'">
            <a-tooltip  overlayClassName="tooltip-box-name">
              <template #title>
                <span>应用名称：{{record.appName}}</span><br>
                <span>应用ID：{{record.autoConfigMchAppId}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.appName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'mchShortName'">
            <a-tooltip  overlayClassName="tooltip-box-name">
              <template #title>
                <span>商户全称：{{record.mchFullName}}</span><br>
                <span>商户简称：{{record.mchShortName}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.mchShortName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key === 'isvNo'">
            <a-tooltip  overlayClassName="tooltip-box-name">
              <template #title>
                <span>渠道名称：{{record.isvName}}</span><br>
                <span>渠道号：{{record.isvNo}}</span>
              </template>
              <div class="my-tooltip-title-box"> {{record.isvName}}</div>
            </a-tooltip>
          </template>
          <template v-if="column.key == 'range'">
            <a-tag v-if="record.range == 0" color="orange">线下场景</a-tag>
            <a-tag v-if="record.range == 1" color="green">线上场景</a-tag>
          </template>
          <template v-if="column.key === 'applyId'">
            <a-popover placement="top" style="background: #0c2640 !important;" v-if="record.state == 1 || record.state == 3">
              <template #content  style="background: #ff0 !important;">
                <p>商户号：{{ record.applyId }}</p>
                <p>上游通道请求单号：{{ record.channelApplyNo }}</p>
              </template>
              <a @click="detailFunc(record.applyId)"  v-if="$access('ENT_MCH_APPLYMENT_ADVANCE')"><b>{{ record.applyId }}</b></a>
              <a  v-if="!$access('ENT_MCH_APPLYMENT_ADVANCE')"><b>{{ record.applyId }}</b></a>
            </a-popover>
            <view v-else>
              <a @click="detailFunc(record.applyId)"  v-if="$access('ENT_MCH_APPLYMENT_ADVANCE')"><b>{{ record.applyId }}</b></a>
              <a  v-if="!$access('ENT_MCH_APPLYMENT_ADVANCE')"><b>{{ record.applyId }}</b></a>
            </view>
          </template>

          <template v-if="column.key === 'merchantType'">
            {{
              record.merchantType === 1
                ? "小微"
                : record.merchantType === 2
                ? "个体"
                : record.merchantType === 3
                ? "企业"
                : "其他组织"
            }}
          </template>

          <template v-if="column.key === 'operation'">
            <!-- 商户系统： 修改按钮多一个 8 预审拒接的判断，  没有参数配置。 其他是通用的。  -->
            <JeepayTableColumns>
              <a-button
                v-if="
                  $access('ENT_MCH_APPLYMENT_EDIT') &&
                  (record.state == 3 || record.state == 8)
                "
                type="link"
                @click="editOrViewFunc(record.applyId, false)"
                >修改</a-button
              >
              <a-button
                  v-if="$access('ENT_MCH_APPLYMENT_VIEW') && (record.state == 2 || record.state == 5)"
                  type="link"
                  @click="editOrViewFunc(record.applyId, true)"
              >详情</a-button
              >
              <a-button
                v-if="$access('ENT_MCH_APPLYMENT_EDIT') && record.state == 0"
                type="link"
                @click="editOrViewFunc(record.applyId, false)"
                >继续填写</a-button
              >
              <a-button
                  v-if="$access('ENT_MCH_APPLYMENT_ADVANCE')"
                  type="link"
                  @click="detailFunc(record.applyId)"
              >进件信息</a-button
              >
              <a-button
                v-if="$access('ENT_MCH_APPLYMENT_COPY')"
                type="link"
                @click="
                  toCopySelectIfCodePage(
                    record.range,
                    record.applyId,
                    record.mchNo
                  )
                "
                >复用信息</a-button
              >

              <!-- 审核中、 待验证、 签约完成 -->
              <a-button
                v-if="
                  $access('ENT_MCH_APPLYMENT_GET_INFO') &&
                  (record.state == 1 || record.state == 4 || record.state == 5)
                "
                type="link"
                @click="queryChannelState(record.applyId, record.state)"
              >
                获取最新结果
              </a-button>

              <!--  2进件成功、 4待验证、 5待签约、 6签约完成/审核成功 -->
              <a-button  @click="oauthFuncButton(record.applyId,record.state)"  v-if="record.ifCode != 'zftpay' && $access('ENT_MCH_APPLYMENT_SIGN') && ( record.state == 2 ||  record.state == 4 ||   record.state == 5 || record.state == 6 ||  record.state == 100)" type="link" >
                <span v-if="record.state == 2" >实名认证</span>
                <span v-else >签约开通</span>
              </a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>

      <a-modal
        v-model:visible="vdata.qrCodeVisible"
        title="商户签约二维码"
        :footer="null"
        :width="250"
        @ok="() => (vdata.qrCodeVisible = false)"
      >
        <QrcodeVue :value="vdata.confirmUrl" :size="200" />
      </a-modal>
      <!-- 微信签约弹窗 -->
      <a-modal
        v-model:visible="vdata.wxQrCodeVisible"
        title="二维码"
        :footer="null"
        :width="250"
        @ok="() => (vdata.wxQrCodeVisible = false)"
      >
        <span>请超级管理员使用微信扫描二维码，根据页面指引完成签约</span>
        <img :src="vdata.confirmUrl" style="width: 200px; height: 200px" />
      </a-modal>
      <!-- 收付通签约弹窗 -->
      <a-modal
        v-model:visible="vdata.sftQrCodeVisible"
        title="二维码"
        :footer="null"
        :width="250"
        @ok="() => (vdata.sftQrCodeVisible = false)"
      >
        <span>请超级管理员使用微信扫描二维码，根据页面指引完成签约</span>
        <QrcodeVue
          :value="vdata.confirmUrl"
          style="padding-top: 10px"
          :size="200"
        />
      </a-modal>
    </a-card>

    <!-- 定义组件分为： 第一步和第二步  -->
    <a-card>
      <component
        :is="vdata.currentApplyPage.component"
        :channelNo="111111"
        :channelAppId="66666"
        ref="applyPageComponentRef"
        @switchApplyPage="switchApplyPage"
      />
    </a-card>

    <!-- 签约开通 弹层 -->
    <NextBizsDrawer ref="nextBizsDrawerRef" />

    <!-- 详情页面组件  -->
    <InfoDetail ref="infoDetail" :callback-func="searchFunc" />

    <a-modal
      v-model:visible="vdata.visibleAdd"
      title=""
      :footer="null"
      width="50%"
      @cancel="handleCancel"
      class="set-img-box"
    >
      <div class="state-box-div">
        <div>
          <img :src="vdata.banerapps" alt="" />
          <div class="left-bottom">
            <a-button type="primary" @click="addFunc('', 1)"
              >发起进件
            </a-button>
          </div>
        </div>
      </div>
      <div class="state-box-div">
        <div class="state-box">
          <img :src="vdata.xianxiaImg" alt="" />
        </div>
        <div class="state-box">
          <img :src="vdata.xianshangImg" alt="" />
          <div class="right-bottom">
            <a-button type="primary" @click="addFunc('', 2)">发起进件</a-button>
          </div>
        </div>
      </div>
    </a-modal>
  </page-header-wrapper>

  <JeepayMchOauth2 v-show="vdata.visibleOauth2" ref="jeepayMchOauth2Ref" />
</template>
<script setup lang="ts">
import {
  API_URL_MCH_APPLYMENT_LIST,
  req,
  $getMchApplymentChannelState,
} from "@/api/manage";
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  provide,
  computed,
} from "vue";
import QrcodeVue from "qrcode.vue";
import ApplySelectMchAndIfcode from "@/components/link/JeepayUIComponents/JeepayMchApplyment/JeepayMchApplymentSelectMchAndIfcode.vue";
import ApplyMchDetailInfoEntry from "@/components/link/JeepayUIComponents/JeepayMchApplyment/JeepayMchApplymentDetailInfoEntry.vue";
import NextBizsDrawer from "./NextBizsDrawer.vue";
// import InfoDetail from "./Detail.vue";
import InfoDetail from "./NewDetail.vue";
import { useRouter } from "vue-router";

const router = useRouter(); //这是全部路由
/** 定义全部组件 **/
const allApplyPage = {
  list: { name: "列表", component: null },
  applySelectMchAndIfcode: {
    name: "选择进件渠道",
    component: ApplySelectMchAndIfcode,
  },
  applyMchDetailInfoEntry: {
    name: "填写进件资料",
    component: ApplyMchDetailInfoEntry,
  },
};

// 动态组件
const jeepayMchOauth2Ref = ref();
const applyPageComponentRef = ref();
const nextBizsDrawerRef = ref();
const infoDetail = ref();
const stateRef = ref();
const dateRangePicker = ref();

const { $infoBox, $access } =
  getCurrentInstance()!.appContext.config.globalProperties;

const infoTable = ref();
let tableColumns = reactive([
  { key: "applyId", dataIndex: "applyId", fixed: "left", title: "商户号", align: "center" },
  { key: "mchShortName", title: "商户简称", dataIndex: "mchShortName" },
  { key: "ifName", title: "支付通道", dataIndex: "ifName" },
  { key: "isvNo", title: "所属渠道", dataIndex: "isvNo" },
  { key: "merchantType", title: "商户类型", dataIndex: "merchantType" },
  { key: "state", title: "进件状态" },
  { key: "autoConfigMchAppId",title: "所属应用", dataIndex: "autoConfigMchAppId",},
  { key: "range", title: "应用类型" },
  { key: "lastApplyAt", dataIndex: "lastApplyAt", title: "最后提交日期" },
  { key: "createdAt", dataIndex: "createdAt", title: "创建日期" },
  { key: "operation", title: "操作", fixed: "right", align: "center" },
]);

let vdata: any = reactive({
  visibleOauth2:false,
  banerapps:
    "https://syb-manage.oss-cn-hangzhou.aliyuncs.com/shouyinbei/banerapps.png",
  xianxiaImg:
    "https://syb-manage.oss-cn-hangzhou.aliyuncs.com/shouyinbei/xianxia.png",
  xianshangImg:
    "https://syb-manage.oss-cn-hangzhou.aliyuncs.com/shouyinbei/xianshang.png",
  visibleAdd: false,
  searchData: { queryDateRange: "" }, // 搜索条件

  currentApplyPage: allApplyPage.list, // 当前的步骤组件  null表示列表页
  backupApplyPage: null, // 备份： 用作快速恢复

  mchApplymentData: {}, //商户进件资料

  isView: false, // 是否预览模式

  copyInfoSourceApplyId: "", // 副本资料
  sceneType: 1, //1 线下默认应用 2线上有应用
});

vdata.banerapps = vdata.banerapps + "?time=" + Date.now();
vdata.xianxiaImg = vdata.xianxiaImg + "?time=" + Date.now();
vdata.xianshangImg = vdata.xianshangImg + "?time=" + Date.now();

function handleCancel(e) {
  vdata.visibleAdd = false;
}
// 清空搜索项
const resetFunc = () => {
  dateRangePicker.value.returnSelectModel();
  vdata.searchData = {};
};

// 向所有子组件注入参数 (子组件可直接更改此值)
provide(
  "mchApplymentData",
  computed(() => vdata.mchApplymentData)
);
provide(
  "isView",
  computed(() => vdata.isView)
);

// 向所有子组件注入参数： 配置模式： mgrApplyment / agentApplyment / mchApplyment
provide("configMode", "mchApplyment");

// 向所有子组件注入参数 副本资料来源ID
provide(
  "copyInfoSourceApplyId",
  computed(() => vdata.copyInfoSourceApplyId)
);

// 请求table接口数据
function reqTableDataFunc(params: any) {
  return req.list(API_URL_MCH_APPLYMENT_LIST, params);
}

// 点击【查询】按钮点击事件
function searchFunc() {
  infoTable.value.refTable(true);
}

// 切换步骤： 不清空数据
function switchApplyPage(page) {
  if (page == "applyAddApps") {
    router.push({
      path: "/apps",
    });
    return false;
  }
  vdata.backupApplyPage = vdata.currentApplyPage;
  vdata.currentApplyPage = allApplyPage[page];
  if(page == 'list'){
    vdata.currentApplyPage.component = false
  }

  if (vdata.currentApplyPage && vdata.currentApplyPage.component) {
    nextTick(() => {
      applyPageComponentRef.value.pageRender(vdata.sceneType);
    });
  } else {
    //列表页
    searchFunc(); // 刷新
  }
}
function getVisibleAdd() {
  vdata.visibleAdd = true;
}
function detailFunc(recordId: any) {
  // 进件详情页

  vdata.copyInfoSourceApplyId = ""; // 副本清空。

  infoDetail.value.show(recordId);
}

// 点击【发起进件】的操作
function addFunc(copyInfoSourceApplyId = "", sceneType = 0) {
  vdata.visibleAdd = false;
  vdata.sceneType = sceneType;
  vdata.copyInfoSourceApplyId = copyInfoSourceApplyId;

  vdata.backupApplyPage = null; // 再次点击进件将无法再次恢复
  vdata.mchApplymentData = {};
  req
    .list(API_URL_MCH_APPLYMENT_LIST, { pageNumber: "1", pageSize: 1 })
    .then((res) => {
      if (res.records.length > 0) {
        vdata.mchApplymentData = { mchNo: res.records[0].mchNo };
      }

      //进件数据重置
      vdata.isView = false;
      switchApplyPage("applySelectMchAndIfcode");
    });
}

// 修改资料 然后重新发起进件操作
function editOrViewFunc(applyId, isView) {
  vdata.copyInfoSourceApplyId = ""; // 副本清空。

  vdata.backupApplyPage = null; // 再次点击进件将无法再次恢复
  vdata.isView = isView;

  req
    .getById(API_URL_MCH_APPLYMENT_LIST, applyId, {
      originData: vdata.isView ? "0" : "1",
    })
    .then((res) => {
      let { applyId,  channelApplyNo, mchNo, ifCode,  applyDetailInfo,  applyErrorInfo,   state, isvNo,  autoConfigMchAppId,    range, } = res;
      vdata.mchApplymentData = {
        applyId,  channelApplyNo, mchNo, ifCode, applyDetailInfo,  applyErrorInfo,  state, isvNo,   autoConfigMchAppId, range, };
      switchApplyPage("applyMchDetailInfoEntry");
    });
}

// 查询最新状态
function queryChannelState(applyId, currState) {
  $getMchApplymentChannelState(applyId).then((res) => {
    if (currState != res.state) {
      $infoBox.message.success("状态已更新");
      searchFunc(); // 更新列表
    } else {
      $infoBox.message.info("状态无变化");
    }
  });
}

// 显示二维码图片
function showQrImgFunc(record) {
  if (record.ifCode == "wxpay") {
    vdata.wxQrCodeVisible = true;
  } else if (record.ifCode == "sftpay") {
    vdata.sftQrCodeVisible = true;
  } else if (record.ifCode == "fuioupay") {
    vdata.qrCodeVisible = true;
    vdata.confirmUrl = JSON.parse(record.applyErrorInfo).signUrl;
    return;
  } else {
    vdata.qrCodeVisible = true;
  }
  vdata.confirmUrl = record.applyErrorInfo;
}

// 副本 copySourceApplyId : 需要copy的资料来源。
function toCopySelectIfCodePage(range, copySourceApplyId, mchNo) {
  const sceneType = parseInt(range) + 1;
  vdata.searchData.mchNo = mchNo;
  addFunc(copySourceApplyId, sceneType);
}
function oauthFunc(applyId) {
  vdata.visibleOauth2 = true;
  jeepayMchOauth2Ref.value.show(applyId);
}

function oauthFuncButton(applyId,state){
  if(state == 2){
    oauthFunc(applyId)
  }else{
    nextBizsDrawerRef.value.show(applyId)
  }
}
</script>
<style>
.state-box-div {
  width: 100%;
  padding: unset !important;
}
.state-box-div img {
  width: 100%;
  height: 100%;
}
.set-img-box .ant-modal-body {
  padding: unset !important;
}
.state-box {
  padding: unset !important;
}

.state-box {
  width: 50%;
}
.state-box img {
  width: 100%;
  height: 100%;
}
.visibleAdd-img {
  //display: flex;
}
.ant-modal-content svg {
  color: #ffffff;
  font-weight: bold;
  font-size: 25px;
}
.left-bottom {
  border-radius: 10px;
  position: absolute;
  left: 5%;
  bottom: 5%;
}
.left-bottom button {
  border-radius: 10px;
}
.right-bottom {
  position: absolute;
  right: 35%;
  bottom: 5%;
}
.right-bottom button {
  border-radius: 10px;
}

</style>