<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker v-if="vdata.showDateTimeRage" ref="dateRangePicker"
            v-model:value="vdata.searchData['queryDateRange']" customDateRangeType="date" />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData['id']" :placeholder="'申请单号'" />
        <jeepay-text-up v-model:value="vdata.searchData.appId" placeholder="应用名称/应用ID" />
        <jeepay-text-up v-model:value="vdata.searchData['productOrPackageName']" :placeholder="'产品名称'" />
        <jeepay-text-up v-model:value="vdata.searchData['contactsName']" :placeholder="'联系人'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.state" placeholder="开通状态">
            <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>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable ref="infoTable" :init-data="false" :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns" :search-data="vdata.searchData" row-key="id" :expandedRowShow="true"
        @btnLoadClose="btnLoading = false" @handleTableChange="handleChange">
        <template #headerCell="{ column }">
          <span v-if="column.tooltipTitle">
            {{ column.title }}
            <a-tooltip :title="column.tooltipTitle"><info-circle-outlined /></a-tooltip>
          </span>
        </template>

        <template #expandedRowRender="{ record }">
          <a-table :columns="vdata.innerColumns" :data-source="record.specialCertificationText" :pagination="false"
            style="margin-top: 5px">
            <template #certificationUrl="{ record }">
              <a-image :src="record.certificationUrl" style="width: 100px;height: 100px" />
            </template>
            <template #UserUrl="{ record }">
              <a-image v-if="record.UserUrl" :src="record.UserUrl" style="width: 100px;height: 100px" />
              <span v-else style="color:#ff4949">未上传</span>
            </template>
          </a-table>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'costRule'">
            <div v-for="item in record.costRule" :key="item">
              {{ item.versionName }}
            </div>
          </template>

          <template v-if="column.key === 'actualPrice'">
            <!--            <div v-for="item in record.costRule" :key="item">-->
            <!--              {{item.sellingPrice}}-->
            <!--            </div>-->

            <a-popover placement="top" style="background: #0c2640 !important;">
              <template #content style="background: #ff0 !important;">
                <p>实付金额：￥{{ record.pracPrice }}</p>
              </template>
              <b style="color: #1890ff">￥{{ record.actualPrice }} </b>
            </a-popover>
          </template>

          <template v-if="column.key === 'appName'">
            <a-tooltip class="my-tooltip" overlayClassName="tooltip-box-name">
              <template #title>
                <span>应用名称：{{ record.appName }}</span><br>
                <span>应用ID：{{ record.appId }}</span>
              </template>
              <div class="my-tooltip-title-box"> {{ record.appName }}</div>
            </a-tooltip>
          </template>

          <template v-if="column.key === 'state'">
            <a-badge status="warning" v-if="record.state == 1" text="审核中" />
            <!--            <a-badge status="processing"  text="审核失败" />-->
            <!--            <a-badge  status="processing" text="待签约" />-->
            <a-badge status="success" v-if="record.state == 3" text="审核通过" />
            <a-badge status="error" v-if="record.state == 2" text="审核失败" />
            <a-badge status="default" v-if="record.state == 4" text="已失效" />
            <!--            <a-tooltip  :title="record.errMsg" v-if="record.state == 3">-->
            <!--              <info-circle-outlined style="color: #FFD080;margin-left: 10px"/>-->
            <!--            </a-tooltip>-->
            <a-tooltip v-if="record.state == 2" :title="record.stateDesc">
              <info-circle-outlined style="color: #FFD080;margin-left: 10px" />
            </a-tooltip>
          </template>

          <template v-if="column.key == 'op'">
            <!-- 操作列插槽 -->
            <!--            <a-button  type="link" >付款</a-button>-->
            <!--            <a-button  type="link" >签约</a-button>-->
            <a-button v-if="record.state == 2" type="link" @click="edit(record)">修改</a-button>
            <!--            <a-button  type="link" >查看详情</a-button>-->
            <!--            <a-button  type="link" >续约</a-button>-->
          </template>
        </template>
      </JeepayTable>
    </a-card>

    <a-drawer v-if="vdata.visible" title="修改" placement="right" :closable="false" width="700px"
      v-model:visible="vdata.visible" :after-visible-change="afterVisibleChange">
      <a-form :model="vdata.editForm" :label-col="{ span: 4 }">
        <a-form-item label="关联应用" v-if="vdata.orderFormState.appId">
          <a-select v-model:value="vdata.orderFormState.appId" placeholder="选择应用" show-search :filter-option="false">
            <a-select-option v-for="(item) in vdata.filteredAppInfoList" :key="item.appId">{{ item.appName }}
              [{{ item.appId as any }}]
              <span v-if="vdata.productDetail.bindingAppList">{{
                vdata.productDetail.bindingAppList.indexOf(item.appId as any) === -1 ? '未关联' : '已关联' }}</span>
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="订购信息">
          <a-col :span="24" style="margin:10px 0px;">
            <a-table :columns="vdata.columns" ref="tableRef" :data-source="vdata.costRule" :pagination="false"
              style="margin-left: -1px;"
              :row-selection="{ selectedRowKeys: vdata.selectedRowKeys, type: 'radio', onChange: onSelectionChange }"
              rowKey="key">
              <template #customTitle>
                <span>
                  产品名称
                </span>
              </template>
              <template #versionName="{ text }">
                <div style="display: flex; align-items: center;">
                  <span>{{ text }}</span>
                </div>
              </template>

              <template #validTime="{ text }">
                <div style="display: flex; align-items: center;">
                  <span>{{ text === -1 ? '长期' : text }}</span>
                </div>
              </template>
              <template #sellingPrice="{ text }">
                <span>
                  {{ text }}
                </span>
              </template>

              <template #lineationPrice="{ text }">
                <span>
                  {{ text }}
                </span>
              </template>

              <template #countPrice="{ record }">
                <span style="color: #f00;">{{ record.sellingPrice == '免费' ? '免费' : record.count * record.sellingPrice
                  + '元' }}</span>
              </template>
            </a-table>
          </a-col>
        </a-form-item>

        <a-form-item label="备注(可选)" name="remark">
          <a-textarea v-model:value="vdata.orderFormState.remark" :rows="1" />
        </a-form-item>

        <a-form-item label="姓名" required>
          <a-input v-model:value="vdata.orderFormState.contactsName" />
        </a-form-item>
        <a-form-item label="手机号" required>
          <a-input v-model:value="vdata.orderFormState.contactsTel" maxlength="11"
            onkeyup="value=value.replace(/\D+/,'')" />
        </a-form-item>

        <a-form-item label="特殊资质" v-if="vdata.specialCertificationText">
          <a-col :span="24" style="margin:10px 0px;">
            <div style="display: flex;flex-wrap: wrap;">
              <div class="upload-box" v-for="(item, index) in vdata.specialCertificationText" :key="index"
                style="margin-right: 20px;text-align: center;">
                <div>{{ item.certificationName }}</div>
                <JeepayUpload v-model:src="item.UserUrl" bizType="applyment" :imgSize="1" class="upload-box-img" />
                <a class="color-box-span" @click="getImg(item)">查看示例</a>
              </div>
            </div>
          </a-col>
        </a-form-item>

        <!--        <a-form-item label="特殊资质名称" required>-->
        <!--          <a-input v-model:value="vdata.orderFormState.specialCertificationText[0].certificationName" />-->
        <!--        </a-form-item>-->
        <!--        <a-form-item label="特殊资质图片" required>-->
        <!--            <JeepayUpload :src="vdata.orderFormState.specialCertificationText[0].certificationUrl" @update:src="updateSrc" bizType="oem" />-->
        <!--            <span class="jeepay-tip-text">建议最小尺寸：220*220px，不超过2.9M</span>-->
        <!--        </a-form-item>-->


      </a-form>

      <div :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }">
        <a-button style="margin-right: 8px" @click="vdata.visible = false">取消</a-button>
        <a-button type="primary" @click="onSubmit">确认修改</a-button>
      </div>
    </a-drawer>


  </page-header-wrapper>
</template>

<script lang="ts" setup>
import { req, $exportExcel, exportExcelUrl, API_URL_PACKAGE_ORDER, API_URL_MCH_APP } from '@/api/manage'
import { ref, reactive, onMounted, nextTick, getCurrentInstance } from 'vue'
import fileDownload from 'js-file-download'
import { useRoute } from 'vue-router'
import dateUtil from '@/utils/dateUtil.js'
import $infoBox from "@/utils/infoBox";
const { $viewerApi } = getCurrentInstance()!.appContext.config.globalProperties

const infoTable = ref()
const dateRangePicker = ref()

let tableColumns = reactive([
  { key: 'id', title: '申请单号', dataIndex: 'id', },
  { key: 'productOrPackageName', title: '产品名称', dataIndex: 'productOrPackageName', },
  { key: 'appName', title: '所属应用', dataIndex: 'appName', },
  { key: 'costRule', title: '订购信息', dataIndex: 'costRule', },
  // { key: 'specialCertificationText', title: '特殊资质', dataIndex: 'specialCertificationText', },
  { key: 'actualPrice', title: '订单金额', dataIndex: 'originPrice', },
  { key: 'state', title: '开通状态', dataIndex: 'state', },
  { key: 'createdAt', title: '创建时间', dataIndex: 'createdAt', },
  { key: 'op', title: '操作', dataIndex: 'op', },
])

let btnLoading = ref(false)
let count: any = ref([]) // 数据统计数组

const vdata: any = reactive({
  visible: false,  //抽屉标识
  orderFormState: {} as any,
  showDateTimeRage: false,
  searchData: { queryDateRange: 'today', method: 'store', sortField: 'payAmount', sortOrder: 'descend' },
  columns: [
    {
      dataIndex: 'versionName',
      key: 'versionName',
      slots: { title: 'customTitle', customRender: 'versionName' },
    },
    {
      title: '周期',
      dataIndex: 'validTime',
      key: 'validTime',
      slots: { customRender: 'validTime' },
    },
    {
      title: '单价',
      key: 'sellingPrice',
      dataIndex: 'sellingPrice',
    },
    {
      title: '划线价',
      key: 'lineationPrice',
      dataIndex: 'lineationPrice',
    },
  ],
  costRule: [],
  selectedRowKeys: [],
  filteredAppInfoList: [],
  mchAppList: [],
  productDetail: {
    bindingApp: 1,
    bindingAppList: [] as any
  } as any,
  appId: '' as any,
  specialCertificationText: [],
  certificationColumns: [
    {
      title: '名称',
      key: 'certificationName',
      dataIndex: 'certificationName',
    },
    {
      key: 'certificationUrl',
      dataIndex: 'certificationUrl',
      title: '图片',
      slots: { customRender: "certificationUrl" },
    },
    {
      title: '类型',
      key: 'inputType',
      dataIndex: 'inputType',
    },
  ],
  ZZselectedRowKeys: [],
  innerColumns: [
    {
      title: '特殊资质名称',
      key: 'certificationName',
      dataIndex: 'certificationName',
    },
    {
      title: '图片',
      key: 'UserUrl',
      dataIndex: 'UserUrl',
      slots: { customRender: "UserUrl" },
    }, {
      title: '示例图',
      key: 'certificationUrl',
      dataIndex: 'certificationUrl',
      slots: { customRender: "certificationUrl" },
    },
  ]
})

async  function getMchApp () {
  let res = await req.list(API_URL_MCH_APP, { pageSize: -1, state: 1 })
  vdata.mchAppList = res.records
  vdata.filteredAppInfoList = res.records
}


function updateSrc(data) {
  vdata.orderFormState.specialCertificationText[0].certificationUrl = data
}

getMchApp()

onMounted(() => {

  searchFunc()
  vdata.showDateTimeRage = true
})

function handleChange(sorter) {
  vdata.searchData['sortField'] = sorter.columnKey
  vdata.searchData['sortOrder'] = sorter.order
}

function afterVisibleChange() { }

const onSelectionChange = (selectedRowKeys, selectedRows) => {
  vdata.selectedRowKeys = selectedRowKeys;
  vdata.orderFormState.costRule = selectedRows
}


let tableRef = ref()
function edit(record) {
  vdata.orderFormState = record
  vdata.selectedRowKeys[0] = record.costRule[0].key
  vdata.ZZselectedRowKeys[0] = record.specialCertificationText[0].key

  if (record.packageOrProduct === 0) {
    req.list('/api/product/getProductById', { productId: record.productId }).then((res) => {
      vdata.specialCertificationText = res.specialCertificationText
      vdata.costRule = res.productText
    })
  } else {
    req.list('/api/packageInfo/getPackageById', { packageId: record.packageId }).then((res) => {
      vdata.specialCertificationText = res.specialCertificationText
      vdata.costRule = res.packageText
    })
  }
  vdata.visible = true
}
function resetFunc() {
  dateRangePicker.value.returnSelectModel()
  vdata.searchData = { method: 'store', queryDateRange: 'today', sortField: 'payAmount', sortOrder: 'descend' }
}

// 请求table接口数据
function reqTableDataFunc(params: any) {
  // params.method = 'store'

  if (!params.sortField) {
    // params.sortField = 'payAmount'
    // params.sortOrder = 'descend'
  }

  return req.list(API_URL_PACKAGE_ORDER, params)
}

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

function onSubmit() {
  vdata.orderFormState.specialCertificationText = vdata.specialCertificationText
  req.updateById('/api/packageInfo', vdata.orderFormState.id, vdata.orderFormState).then((res) => {
    $infoBox.message.success('更新成功')
    searchFunc()
    vdata.visible = false
  })
}

const onSelectioncertificationChange = (selectedRowKeys, selectedRows) => {
  vdata.ZZselectedRowKeys = selectedRowKeys;
  vdata.orderFormState.specialCertificationText = selectedRows
}

function getImg(item) {
  $viewerApi({ images: [item.certificationUrl] })
}
</script>