<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="selectHandle">
              <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="onlyMineChange" 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="el-icon-search"
          placeholder="姓名/公司名称"
          @input="searchHandle"
        ></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 slot-scope="{row}">
            <span v-if="column.key==='approveType'">
              {{row['approveType']===0?'申请账号':'申请启用'}}
            </span>
            <!-- 如果字段名一样,但展示文字不同 可以用这种方法 -->
            <!-- <span v-else-if="column.key==='status'&&(Role.includes('admin')||listType==='all')">
              {{ApprovalStatus[row['status']]}}
            </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 slot-scope="{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>
      <el-pagination
					layout="total,prev,pager,next,jumper" 
					background
					:current-page="currentPage"
					@current-change="handleCurrentChange"
					:page-size="pageSize" 
					:total="total"
					style="text-align:right;margin-top:30px;">
			</el-pagination>
    </div>
    <!-- 申请账号审批/申请启用审批 弹窗 -->
    <apply-approval-dialog 
      :isApplyApprovalDialogShow.sync="isApplyApprovalDialogShow"
      :applyInfo="applyInfo"
      @approved="getTableData"
    />
    <!-- 申请启用 弹窗 -->
    <add-apply-hint-dialog 
      :isAddApplyHintShow.sync="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>

<script>
import AddApplyHintDialog from './compontents/addApplyHintDialog.vue';
import applyApprovalDialog from './compontents/applyApprovalDialog.vue';
import{etaTrialColumn,
       adminApprovalList,
       approvedList,
       ApprovalStatus}from './config';
import{etaTrialInterence}from '@/api/modules/crmApi.js';
export default {
  components: { applyApprovalDialog, AddApplyHintDialog },
  data() {
    return {
      /* 页面配置 */
      currentPath:'',//当前路由,用于确定columnList,canEdit,tableData
      approvalNum: 0,//还剩多少条待审批
      searchText: "",//搜索框文字
      onlyMine:false,// 是否只是我申请的
      listType: "all",//非管理员-列表类型,当角色为非管理员时,与当前路由一起确定table
      approvalState: 2,//管理员-审批列表的默认选项
      approvalStateArr: [
        { key: 2, label: "待审批" },
        { key: 3, label: "已审批" },
        { key: 1, label: "全部" },
      ],//管理员-审批列表的可选项
      ApprovalStatus:ApprovalStatus,//所有的审批状态
      /* table */
      canEdit:false,//是否显示操作栏
      tableData:[],//表格数据
      columnList:[],//表格列
      tableLoading:false,//表格loading
      sortKeys:[
        'Expiration','ModifyTime','LastLoginTime','ActiveTime',
        'IndexNum','ChartNum','LoginNum','LastLoginDuration'
      ],//需要排序的字段
      SortParam:'',//排序字段
      SortType:'',//升序降序
      applyInfo:{},//当前选择的表格数据(经格式转换)
      /*分页 */
      currentPage:1,
      pageSize:10,
      total:1,
      /* 弹窗 */
      isApplyApprovalDialogShow:false,
      isAddApplyHintShow:false,
      showDetailDialogShow:false
    };
  },
  computed: {
    Role() {
      return localStorage.getItem("Role");
    },
  },
  watch: {
    '$route.path'(newval){
      this.currentPath = newval
      this.currentPage=1
      this.SortParam=''
      this.SortType=''
      this.approvalState=2
      this.searchText=''
      this.getTableData()
    },
    listType(val){
      this.currentPage=1
      this.SortParam=''
      this.SortType=''
      this.approvalState=2
      this.searchText=''
      this.getTableData()
    }
  },
  methods: {
    getTableData(){
      this.tableLoading=true
      //获取columnList和tableData
      let interenceName = ''
      //确定是 ETA试用列表 还是 审批列表
      if(this.currentPath=='/etaTrialList'){
        this.canEdit = false
        this.columnList = etaTrialColumn
        interenceName = 'getETATrialList'
      }else if(this.currentPath=='/etaApprovalList'){
        this.canEdit = true
        //管理员-审批列表
        if(this.Role.includes('admin')){
          this.columnList = adminApprovalList
          interenceName='getAdminApprovalList'
        }
        //非管理员-我的审批
        if(!this.Role.includes('admin')&&this.listType=='all'){
          this.columnList = adminApprovalList
          interenceName='getApprovalAllList'
        }
        //非管理员-账号列表
        if(!this.Role.includes('admin')&&this.listType!='all'){
          this.columnList = approvedList
          interenceName='getApprovalList'
        }
      }
      etaTrialInterence[interenceName]({
          PageSize:this.pageSize,
          CurrentIndex:this.currentPage,
          KeyWord:this.searchText,
          SortParam:this.SortParam,
          SortType:this.SortType,
          ListParam:this.approvalState,
          IsOnlyMe:this.onlyMine
        }).then((res)=>{
          if(res.Ret!==200) return 
          const {List,Paging,ApprovalNum} = res.Data
          this.tableData = List||[]
          this.total = Paging.Totals
          this.approvalNum = ApprovalNum||0
          this.tableLoading=false
        })
     /*  this.$nextTick(()=>{
        this.tableLoading=false
      }) */
    },
    sortChangeHandle({prop,order}){
      this.SortParam = prop
      this.SortType = order?order==='ascending'?'asc':'desc':''
      this.currentPage=1
      this.getTableData()
    },
    searchHandle(){
      this.currentPage=1
      this.getTableData();
    },
    selectHandle(change){
      this.currentPage=1
      this.ListParam=change
      this.getTableData()
    },
    onlyMineChange(){
      this.currentPage=1
      this.getTableData()
    },
    changePath(path){
      if(this.currentPath===path) return
      this.currentPath = path
      this.$router.push(path)
    },
    toQuestionnaireSurvey(){
      this.$router.push('/questionnaireSurvey')
    },
    handleCurrentChange(pageNo){
      this.currentPage=pageNo
      this.getTableData()
    },
    //将表格数据转换成applyInfo的形式
    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]
      this.applyInfo = temp
    },
    async handleOperate(type,data){
      this.getApplyInfo(type,data)
      //审批 申请启用 重新申请 是弹窗
      //审批
      if(type==='approve'){
        this.isApplyApprovalDialogShow = true
      }
      //申请启用
      if(type==='active'){
        this.isAddApplyHintShow = true
      }
      //重新申请
      if(type==='apply'){
        const {ApplyMethod} = data
        //如果是申请账号,则跳转至新增申请页面
        if(ApplyMethod===1){
          sessionStorage.setItem('applyInfo',JSON.stringify(this.applyInfo))
          this.$router.push('/etaAddApproval')
        }
        //如果是申请启用,则显示弹窗
        else{
          this.isAddApplyHintShow = true
        }
      }
      //驳回理由 撤回 删除 是 MessageBox
      //撤回
      if(type==='withdraw'){
        //调撤回接口 getTableData()
        const res = await etaTrialInterence.withdrawApproval({
          Mobile:data.Mobile
        })
        if(res.Ret!==200) return
        this.$confirm('', '撤回成功', {
          confirmButtonText: '重新申请',
          cancelButtonText: '取消',
          cancelButtonClass: "btn-custom-cancel",
          type: 'success',
          center: true
        }).then(() => {
          const {ApplyMethod} = data
          if(ApplyMethod===1){
            sessionStorage.setItem('applyInfo',JSON.stringify(this.applyInfo))
            this.$router.push('/etaAddApproval')
          }
          else{
            this.isAddApplyHintShow = true
          }
        }).catch(() => {
          this.getTableData()
        });
      }
      //驳回理由
      if(type==='checkReplay'){
        this.$confirm(data.ApprovalRemark||'', '驳回理由', {
          confirmButtonText: '知道了',
          showCancelButton:false,
        }).then(() => {}).catch(() => {});
      }
      //删除 二次确认
      if(type==='delete'){
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          //调删除接口
          etaTrialInterence.deleteApproval({
            ApprovalId:data.ApprovalId
          }).then(res=>{
            if(res.Ret!==200) return 
            this.getTableData()
            this.$message.success('删除成功')
          })
        }).catch(() => {});
      }
      //展示账号密码
      if(type==='showDetail'){
          this.showDetailDialogShow = true
      }
    },
    closeDialog(){
      this.isAddApplyHintShow = false
      this.getTableData()
    }
  },
  //如果需要刷新时存listType 用beforeRouteLeave
  mounted(){
    this.currentPath = this.$route.path
    this.listType = sessionStorage.getItem('etaApprovalListType')||'all'
    sessionStorage.removeItem('etaApprovalListType')
    this.getTableData()
  }
};
</script>
<style lang="scss">
.btn-custom-cancel{ 
  float: right;
  margin-left: -100px;
  margin-right: 110px;
}
</style>
<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>
