<template>
  <page-header-wrapper>
    <a-card v-show="vdata.tableType == 'table'" >
      <JeepaySearchForm v-if="$access('ENT_UR_ROLE_SEARCH')" :searchConditionNum="6" :searchFunc="searchFunc" :resetFunc="() => { data.searchData= {} }">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="data.searchData.queryDateRange" customDateRangeType="dateTime" />
        </a-form-item>
        <jeepay-text-up v-if="props.configMode == 'mgr'" v-model:value="data.searchData['mchUserName']" :placeholder="'用户号/名称/手机号'" />

        <jeepay-text-up v-model:value="data.searchData['id']" :placeholder="'申请单号'" />
        <jeepay-text-up v-model:value="data.searchData.appId" placeholder="应用名称/应用ID" />
        <jeepay-text-up v-model:value="data.searchData['contactsName']" :placeholder="'联系人名称/手机号'" />

      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
          ref="infoTable"
          :init-data="true"
          :req-table-data-func="reqTableDataFunc"
          :table-columns="tableColumns"
          :search-data="data.searchData"
          row-key="sysUserId"
          @btnLoadClose="data.btnLoading=false"
      >
        <template #topBtnSlot>
          <div>
            <a-button  type="primary"  class="mg-b-30" v-if="props.configMode == 'mch'"  @click="addFunc" >  <plus-outlined />  新建  </a-button>
          </div>
        </template>
        <template #bodyCell="{column,record}">

          <template v-if="column.key === 'appName'">
            <a-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 === 'costRule'">
            <div v-for="item in record.costRule" :key="item">
              {{ item.versionName }}
            </div>
          </template>

          <template v-if="column.key === 'remark'"  >
<!--            <span @click="remarkFunc(record)" class="two-lines"  v-if="props.configMode == 'mgr'" >-->
<!--              <b><a >{{ record.remark != "" ? record.remark : "&#45;&#45;" }}</a></b>-->
<!--              <EditOutlined @click="remarkFunc(record)" />-->
<!--            </span>-->

<!--            <span class="two-lines"  v-else >-->
<!--              <b>{{ record.remark != "" ? record.remark : "&#45;&#45;" }}</b>-->
<!--            </span>-->
            {{ record.remark }}

          </template>
          <template v-if="column.key === 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button  type="link" @click="showPreAuditModalFunc(record)" v-if="record.taskState == 0">审核</a-button>
              <!--              <a-button  type="link" @click="editFunc(record)">修改</a-button>-->
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>


    <!-- 新增 / 修改 页面组件  -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callback-func="searchFunc" />

    <a-modal v-model:visible="vdata.showPreAuditModal" title="处理审核任务" width="30%" :confirmLoading="vdata.preAuditModalLoading" @ok="preAuditHandleOkFunc">
      <a-form>
        <a-form-item label="业务场景：">
          <JeepayUpload v-model:src="vdata.preAuditResult['taskSceneUrl']" :disabled="true" list-Type="picture"  bizType="notice" />
        </a-form-item>
        <a-form-item label="处理结果：">
          <a-radio-group v-model:value="vdata.preAuditResult.taskState">
            <a-radio :value="1">审核通过</a-radio>
            <a-divider />
            <a-radio :value="2">审核拒绝</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item v-if="vdata.preAuditResult.taskState == 2" label="原因：">
          <a-textarea v-model:value="vdata.preAuditResult.applyErrorInfo" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-card v-show="vdata.tableType == 'detail'" style="background: #f0f2f5; ">

      <SybProductDeatil ref="nextProductDeatilRef"  :configMode="props.configMode" @itemRender="itemRenderSave" />
    </a-card>

    <a-card v-show="vdata.tableType == 'sign'" style="background: #f0f2f5; ">

      <SybProductSign ref="nextProductSignRef" :configMode="props.configMode" @itemRender="itemRenderSave" />
    </a-card>

    <a-modal
        v-model:visible="vdata.visibleNotes"
        title="编辑备注"
        :footer="null"
        width="50%"
        @cancel="handleCancel"
    >
      <div style="overflow: auto">
        <div
            class="code code-layout-item"
            style="display: flex; justify-content: center"
        >
          <a-form-item label="备注" required style="width: 80%">
            <a-textarea
                v-model:value="vdata.notes.value"
                placeholder="请输入备注"
                :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-item>
        </div>

        <div style="text-align: center; margin-top: 34px">
          <a-button
              type="primary"
              :disabled="vdata.isDisabled"
              @click="sendNotes()"
          >
            确定
          </a-button>
        </div>
      </div>
    </a-modal>
  </page-header-wrapper>
</template>
<script setup lang="ts">
import {
  req,
  reqLoad,
  API_URL_PAY_TASK_DEL,
  API_URL_PAY_TASK_SAVE,
  $applymentTaskListPreAudit,
  API_URL_PRODUCT_EXAMINE_LIST,
  API_URL_PRODUCT_START_LIST
} from '@/api/manage'
import { useUserStore } from '@/store/modules/user'
// import InfoAddOrEdit from './AddOrEdit.vue'

import { reactive,ref,getCurrentInstance} from 'vue'
import {useRouter} from "vue-router";

const router = useRouter() //这是全部路由
const userStore = useUserStore()
const { $infoBox, $access, $hasAgentEnt } = getCurrentInstance()!.appContext.config.globalProperties

const props = defineProps ({
  configMode: { type: String, default: '' },   // 模式
  callbackFunc: { type: Function, default: () => ({}) },
  apiCode: { type: String, default: '' },   // 模式
})
const tableColumns = reactive([
  {key:'id',title: '申请单号',   dataIndex: 'id' },
  {key:'appName', title: '应用名称',   dataIndex: 'appName' },
  {key:'productOrPackageName', title: '产品名称', dataIndex: 'productOrPackageName', },
  {key:'costRule', title: '版本信息', dataIndex: 'costRule', },
  {key:'contactsName', title: '联系人', dataIndex: 'contactsName', },
  {key:'contactsTel', title: '联系人手机号', dataIndex: 'contactsTel', },
  {key:'remark', title: '备注', dataIndex: 'remark', },
  {key:'createdAt', title: '开通时间', dataIndex: 'createdAt', },
  {key:'end_time', title: '过期时间',fixed: 'right', dataIndex: 'end_time', },
  // {key:'taskState', title: '状态', dataIndex: 'taskState', },
  // {key:'createdAt', title: '创建时间', dataIndex: 'createdAt', },
  // {key: 'op',title: '操作',   fixed: 'right',align: 'center' }
])

const infoTable = ref()
const infoAddOrEdit =ref()
const nextProductDeatilRef = ref();
const nextPackageDeatilRef = ref()
const nextProductSignRef = ref();
const sybProductSphListRef = ref();
const sybProductAqfListRef = ref();

let data : any = reactive ({
  tableColumns: tableColumns,
  searchData: {queryDateRange: ''} as any,
  btnLoading: false
})
let vdata : any = reactive ({
  tableType:"table",
  notes:{} as any,
  showPreAuditModal: false,  // 是否显示预审核弹层
  preAuditModalLoading: false,  // loading
  preAuditResult: {}, // 预审核结果
})

// 请求table接口数据
async  function reqTableDataFunc(params){
  params.state = 3
  params.apiCode = props.apiCode
  let res =  await req.list(API_URL_PRODUCT_EXAMINE_LIST, params)
  for (var i=0;i<res.records.length;i++){
    res.records[i].end_time = addDaysToSpecificDate(res.records[i].createdAt,res.records[i].costRule[0].validTime)
  }
  console.log(res.records,'resrecordsresrecords')
  return res;
}

function addDaysToSpecificDate(date, days) {
  let resultDate = new Date(date);

  // 在指定日期基础上添加指定天数
  resultDate.setDate(resultDate.getDate() + days);

  // 获取年、月、日
  let year = resultDate.getFullYear();
  let month = (resultDate.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1，并保证两位数
  let day = resultDate.getDate().toString().padStart(2, '0'); // 保证两位数

  let hours = resultDate.getHours().toString().padStart(2, '0'); // 保证两位数
  let minutes = resultDate.getMinutes().toString().padStart(2, '0'); // 保证两位数
  let seconds = resultDate.getSeconds().toString().padStart(2, '0'); // 保证两位数

  // 返回格式化的日期和时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

}

function searchFunc() { // 点击【查询】按钮点击事件
  data.btnLoading = true // 打开查询按钮的loading
  infoTable.value.refTable(true)
}

function addFunc () { // 业务通用【新增】 函数
  // infoAddOrEdit.value.show()
  vdata.tableType = 'detail'
  nextProductDeatilRef.value.show(9)
}

function editFunc (record) { // 业务通用【修改】 函数
  infoAddOrEdit.value.show(record)
}
function delFunc(recordId) { // 业务通用【删除】 函数
  $infoBox.confirmDanger('确认删除？', '', () => {
    return req.delById(API_URL_PAY_TASK_DEL, recordId).then(res => {
      $infoBox.message.success('删除成功！')
      infoTable.value.refTable(false)
    })
  })
}



function onCopySuccess () {
  $infoBox.message.success('复制成功')
}
function  updateState (recordId, state) { // 【更新状态】

  const title = state === 1 ? '确认[启用]？' : '确认[停用]？'
  return new Promise<void>((resolve, reject) => {
    $infoBox.confirmDanger(title, '', () => {
          return reqLoad.updateById(API_URL_PAY_TASK_SAVE, recordId, { taskState: state }).then(res => {
            searchFunc()
            resolve()
          }).catch(err => reject(err))
        },
        () => {
          reject(new Error())
        })
  })
}

// 弹层取消
function handleCancel(e) {
  vdata.visibleNotes = false;
}
// 显示弹层
function showPreAuditModalFunc (record) {

  vdata.copyInfoSourceApplyId = '' // 清空副本信息

  vdata.showPreAuditModal = true
  vdata.preAuditResult = record
}
// 预审核结果
function preAuditHandleOkFunc(){

  if(!vdata.preAuditResult.taskState){
    return $infoBox.message.error('请选择审核结果')
  }

  if( (vdata.preAuditResult.taskState == 2 ) && !vdata.preAuditResult.applyErrorInfo){
    return $infoBox.message.error('请填写拒绝原因')
  }

  $applymentTaskListPreAudit(vdata.preAuditResult.id, {stateDesc:vdata.preAuditResult.stateDesc,taskState:vdata.preAuditResult.taskState}).then((res) => {
    vdata.showPreAuditModal = false
    $infoBox.message.success('处理完成')
    infoTable.value.refTable(true)
  }).finally(() => {
    vdata.preAuditModalLoading = false
  })

}

function remarkFunc(data) {
  vdata.notes.id = data.id;
  vdata.notes.value = data.remark ?? "";
  vdata.visibleNotes = true;
}
function itemRenderSave(e) {
  switch (e.type){
    case 1:
      vdata.tableType = e.table
      nextProductSignRef.value.show(e.productId)
      break;
    case 2:
      vdata.tableType = e.table
      nextProductSignRef.value.show(e.productId)
      break;
    case 3:
      req.add(API_URL_PRODUCT_START_LIST, e).then(data => {
        $infoBox.message.success(data)
        setTimeout(() => {
          router.push({
            path: '/productLog'
          })
        }, 1000)
      })
      break
    case 4:
      router.push({
        path: '/apps'
      })
      break;
    case 6:
      vdata.tableType = e.table
      nextProductDeatilRef.value.show(e.productId)
      break;
    case 7:
      vdata.tableType = e.table
      nextPackageDeatilRef.value.show(e.productId)
      break;
    case 12:
      vdata.tableType = e.table
      sybProductSphListRef.value.show(e.productId)
      break;
    case 13:
      vdata.tableType = e.table
      sybProductAqfListRef.value.show(e.productId)
      break;
  }

}
</script>
<style>

.two-lines {
  color: #1965ff;
  max-width: 150px;
  display: block;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
