<script setup>
import { ref,computed, reactive,toRefs } from 'vue'
import { useRoute,useRouter } from 'vue-router'
import { ElMessageBox,ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import{etaTrialInterence}from '@/api/modules/crmApi.js';
import { useConfig } from './use-config'
import mPage from '@/components/mPage.vue'
import applyApprovalDialog from './compontents/applyApprovalDialog.vue'
import applyHintDialog from './compontents/addApplyHintDialog.vue';

const $route = useRoute()
const $router = useRouter()

const { columnList,canEdit,listType,interenceName,ApprovalStatus } = useConfig()

const Role = computed(() => {
  return localStorage.getItem("Role");
})

const sortKeys =[
  'Expiration','ModifyTime','LastLoginTime','ActiveTime',
  'IndexNum','ChartNum','LoginNum','LastLoginDuration'
]//需要排序的字段

const approvalStateArr = [
  { key: 2, label: "待审批" },
  { key: 3, label: "已审批" },
  { key: 1, label: "全部" },
]//管理员-审批列表的可选项


const tableLoading = ref(false)
const total = ref(0)
const approvalNum = ref(0)//还剩多少条待审批
const tableData = ref([])
const filterParam = reactive({
    searchText: "",//搜索框文字
    onlyMine:false,// 是否只是我申请的
    SortParam:'',//排序字段
    SortType:'',//升序降序
    approvalState: 2,//管理员-审批列表的默认选项
    currentPage:1,
    pageSize:10,
    
})
function getTableData(){

  etaTrialInterence[interenceName]({
      PageSize:filterParam.pageSize,
      CurrentIndex:filterParam.currentPage,
      KeyWord:filterParam.searchText,
      SortParam:filterParam.SortParam,
      SortType:filterParam.SortType,
      ListParam:filterParam.approvalState,
      IsOnlyMe:filterParam.onlyMine
    }).then((res)=>{
      if(res.Ret!==200) return 

      const {List,Paging,ApprovalNum} = res.Data
      tableData.value = List||[]
      total.value = Paging.Totals
      approvalNum.value = ApprovalNum||0
      tableLoading.value=false
    })
}
getTableData()

function sortChangeHandle({prop,order}){
  filterParam.SortParam = prop
  filterParam.SortType = order?order==='ascending'?'asc':'desc':''
  filterParam.currentPage=1
  getTableData()
}

function filterChange() {
  filterParam.currentPage=1
  getTableData()
}

function handleCurrentChange(pageNo){
  filterParam.currentPage=pageNo
  getTableData()
}

function changePath(path){
  if($route.path===path) return

  $router.push(path)
}

function toQuestionnaireSurvey(){
  $router.push({path: '/questionnaireSurvey'})
}


//将表格数据转换成applyInfo的形式
const applyInfo = ref({})//当前选择的表格数据(经格式转换)
function getApplyInfo(type,data){
  //data.ApplyMethod 这条数据是申请账号1,还是申请启用2
  const temp = {applyType:1,applyData:[]}
  temp.applyType = data.ApplyMethod||2
  //重新申请 申请启用时 applyType要设置为0
  if((type==='apply'||type==='withdraw'||type==='approve')&&data.ApplyMethod===2){
    temp.applyType = 0
  }
  if(type==='active'){
    temp.applyType=0
  }
  temp.applyData = [data]
  applyInfo.value = temp
}
/* 弹窗 */
const isApplyApprovalDialogShow = ref(false)
const isAddApplyHintShow = ref(false)
const showDetailDialogShow = ref(false)
async function handleOperate(type,data){
  getApplyInfo(type,data)

  //审批 申请启用 重新申请 是弹窗
  //审批
  if(type==='approve'){
    isApplyApprovalDialogShow.value = true
  }
  //申请启用
  if(type==='active'){
    isAddApplyHintShow.value = true
  }
  //重新申请
  if(type==='apply'){
    const {ApplyMethod} = data
    //如果是申请账号,则跳转至新增申请页面
    if(ApplyMethod===1){
      sessionStorage.setItem('applyInfo',JSON.stringify(this.applyInfo))
      $router.push('/etaAddApproval')
    }
    //如果是申请启用,则显示弹窗
    else{
      isAddApplyHintShow.value = true
    }
  }
  //驳回理由 撤回 删除 是 MessageBox
  //撤回
  if(type==='withdraw'){
    //调撤回接口 getTableData()
    const res = await etaTrialInterence.withdrawApproval({
      Mobile:data.Mobile
    })

    if(res.Ret!==200) return
    ElMessageBox.confirm('', '撤回成功', {
      confirmButtonText: '重新申请',
      cancelButtonText: '取消',
      cancelButtonClass: "btn-custom-cancel",
      type: 'success',
      center: true
    }).then(() => {
      const {ApplyMethod} = data
      if(ApplyMethod===1){
        sessionStorage.setItem('applyInfo',JSON.stringify(applyInfo.value))
        $router.push('/etaAddApproval')
      }
      else{
        isAddApplyHintShow.value = true
      }
    }).catch(() => {
      getTableData()
    });
  }
  //驳回理由
  if(type==='checkReplay'){
    ElMessageBox.confirm(data.ApprovalRemark||'', '驳回理由', {
      confirmButtonText: '知道了',
      showCancelButton:false,
    }).then(() => {}).catch(() => {});
  }
  //删除 二次确认
  if(type==='delete'){
    ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      //调删除接口
      etaTrialInterence.deleteApproval({
        ApprovalId:data.ApprovalId
      }).then(res=>{
        if(res.Ret!==200) return 
        getTableData()
        ElMessage.success('删除成功')
      })
    }).catch(() => {});
  }
  //展示账号密码
  if(type==='showDetail'){
      showDetailDialogShow.value = true
  }
}

const { searchText,onlyMine,approvalState,currentPage,pageSize } = toRefs(filterParam)

</script>
<template>
  <!-- ETA试用列表+审批列表  -->
  <div class="eta-trial-list">
    <div class="table-select">
      <div class="btn-list">
        <template v-if="Role.includes('admin')">
          <!-- 管理员-ETA试用列表 -->
          <template v-if="$route.path==='/etaTrialList'">
            <el-button type="primary" @click="changePath('/etaApprovalList')">审批列表</el-button>
            <div class="approval-hint" v-if="approvalNum">
              ·{{ approvalNum }}条申请记录待审批
            </div>
            <el-button type="primary" @click="toQuestionnaireSurvey" style="margin-left: 30px;">问卷调研</el-button>
          </template>
          <!-- 管理员-审批列表 -->
          <template v-if="$route.path==='/etaApprovalList'">
            <el-select v-model="approvalState" placeholder="请选择" @change="filterChange">
              <el-option
                v-for="item in approvalStateArr"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              >
              </el-option>
            </el-select>
          </template>
        </template>
        <template v-else>
          <!-- 非管理员-ETA试用列表 -->
          <template v-if="$route.path==='/etaTrialList'">
            <el-button type="primary" @click="changePath('/etaAddApproval')">新增申请</el-button>
            <el-button type="primary" plain @click="changePath('/etaApprovalList')" style="margin-left: 30px;">申请列表</el-button>
            <el-button type="primary" @click="toQuestionnaireSurvey" style="margin-left: 30px;">问卷调研</el-button>
            <el-checkbox v-model="onlyMine" @change="filterChange" style="margin-left: 30px;">我申请的</el-checkbox>
          </template>
          <!-- 非管理员-我的审批+账号列表 -->
          <template v-if="$route.path==='/etaApprovalList'">
            <el-radio-group v-model="listType">
              <el-radio-button label="all">我的审批</el-radio-button>
              <el-radio-button label="approved">账号列表</el-radio-button>
            </el-radio-group>
            <el-tooltip class="item" effect="dark" 
              content="该列表为初始账号密码，用于登陆ETA试用平台：https://exptest.hzinsights.com/" 
              placement="right">
              <span class="el-icon-question" style="margin-left:5px;color:#C0C4CC"></span>
            </el-tooltip>
          </template>
        </template>
      </div>
      <div class="search-wrap">
        <el-input
          v-model="searchText"
          :prefix-icon="Search"
          placeholder="姓名/公司名称"
          @input="filterChange"
        ></el-input>
      </div>
    </div>
    <div class="table-wrap">
      <el-table :data="tableData" @sort-change="sortChangeHandle" border v-loading="tableLoading">
        <el-table-column 
          v-for="column in columnList" 
          :key="column.label"
          align="center"
          :prop="column.key"
          :label="column.label"
          :sortable="sortKeys.includes(column.key)?'custom':false"
          :min-width="column.minWidth"
        >
          <template #default="{row}">
            <span v-if="column.key==='approveType'">
              {{row['approveType']===0?'申请账号':'申请启用'}}
            </span>

            <span v-else-if="column.key==='Enabled'&&(!Role.includes('admin')&&listType==='approved')"
              :class="{'color-hint':row['Enabled']===0}"
            >
              {{row['Enabled']===0?'禁用':'启用'}}
            </span>
            <span v-else>
              {{row[column.key]}}
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="canEdit" label="操作" align="center">
          <template #default="{row}">
            <!-- 非管理员-账号列表的操作: 申请启用 -->
            <template v-if="!Role.includes('admin')&&listType==='approved'">
              <el-button type="text" size="small" v-if="row.Enabled===0" @click="handleOperate('active',row)">申请启用</el-button>
            </template>
            <!-- 非管理员-我的审批操作: 撤回,重新申请,删除,驳回理由-->
            <template v-if="!Role.includes('admin')&&listType==='all'">
              <el-button type="text" size="small" v-if="ApprovalStatus[row.ApprovalStatus]===0" @click="handleOperate('withdraw',row)">撤回</el-button>
              <el-button type="text" size="small" v-if="ApprovalStatus[row.ApprovalStatus]>=2" @click="handleOperate('apply',row)">重新申请</el-button>
              <el-button type="text" size="small" v-if="ApprovalStatus[row.ApprovalStatus]===3" @click="handleOperate('checkReplay',row)">驳回理由</el-button>
              <el-button type="text" size="small" v-if="ApprovalStatus[row.ApprovalStatus]===2" class="color-hint" @click="handleOperate('delete',row)">删除</el-button>
              <!-- 已审批通过的:查看密码 -->
              <el-button type="text" size="small" v-if="ApprovalStatus[row.ApprovalStatus]===1" @click="handleOperate('showDetail',row)">账号密码</el-button>
            </template>
            <!-- 管理员-审批列表操作: 审批-->
            <template v-if="Role.includes('admin')">
              <el-button type="text" size="small" v-if="ApprovalStatus[row.ApprovalStatus]===0" @click="handleOperate('approve',row)">审批</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div style="height:40px;margin: 20px 0">
        <m-page
          :page_no="currentPage"
          :pageSize="pageSize"
          :total="total"
          style="margin-top:30px;"
          @handleCurrentChange="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 申请账号审批/申请启用审批 弹窗 -->
    <apply-approval-dialog 
      :isApplyApprovalDialogShow="isApplyApprovalDialogShow"
      :applyInfo="applyInfo"
      @approved="getTableData"
      @close="isApplyApprovalDialogShow=false"
    />
    <!-- 申请启用 弹窗 -->
    <add-apply-hint-dialog 
      :isAddApplyHintShow="isAddApplyHintShow"
      :applyInfo="applyInfo"
      @applyActiveSuccess="getTableData"
      @closeDialog="closeDialog"
    />
      <!-- 查看账号密码弹窗 -->
      <!-- <el-dialog 
        v-if="showDetailDialogShow"
        :visible.sync="showDetailDialogShow"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        :title="`${applyInfo.applyData[0].UserName}——账号密码`"
        width="889px"
        v-dialogDrag
        center
      >
        <div class="apply-detail">
            <p>公司名称：{{applyInfo.applyData[0].CompanyName}}</p>
            <p>账号：{{applyInfo.applyData[0].Account}}</p>
            <p>密码：{{applyInfo.applyData[0].Password}}</p>
            <div class="button">
                <el-button type="primary" @click="showDetailDialogShow=false">知道了</el-button>
            </div>
        </div>

      </el-dialog> -->
  </div>
</template>
<style scoped lang="scss">
.eta-trial-list{
  padding:30px;
  background-color: #fff;
  border-radius: 4px;
  .table-select{
    display: flex;
    justify-content: space-between;
    .btn-list{
      display: flex;
      align-items: center;
      .approval-hint{
        margin-left: 15px;
        border-radius: 4px;
        padding:5px 12px;
        background-color: #FEF0F0;
        color: #F56C6C;
        position: relative;
        &::before{
          content: '';
          position:absolute;
          width:0;
          height:0;
          left:-12px;
          top:calc(50% - 6px);
          border: 6px solid transparent;
          border-right: 6px solid #FEF0F0;
        }
      }
    }
    .search-wrap{
      width:400px;
    }
  }
  .table-wrap{
    margin-top:30px;
  }

  .color-hint{
    color: red;
  }
  .apply-detail{
      display: flex;
      flex-direction: column;
      gap:20px;
      p{
          font-size: 16px;
          margin-left: 20px;
      }
      .button{
          text-align: center;
          padding-bottom: 25px;
      }
  }
}
</style>  