<template>
  <!-- ETA试用列表+审批列表  -->
  <div class="eta-trial-list">
    <div class="table-select">
      <div class="btn-list">
        <template v-if="false">
          <!-- !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> -->
            <div class="tips">*账号用于登录ETA试用平台：https://exptest.hzinsights.com/</div>
            <div class="right-header">
              <span>已选{{selectedTotal}}</span>
              <el-checkbox :indeterminate="isIndeterminate" v-model="isCheckAll" @change="listCheckAllChange" style="margin-left: 40px;">列表全选</el-checkbox>
            </div>
          </template>
        </template>
      </div>
      <div class="search-wrap">
        <template v-if="$route.path==='/etaApprovalList'">
          <el-button type="primary" @click="batchMove">批量移动</el-button>
          <el-button type="primary" @click="batchOperate">一键启用</el-button>
        </template>
        <el-input
          v-model="searchText"
          prefix-icon="el-icon-search"
          placeholder="姓名/公司名称"
          @input="searchHandle"
          style="width: 400px; margin-left: 20px;"
        ></el-input>
      </div>
    </div>
    <div class="table-wrap">
      <el-table :data="tableData" @sort-change="sortChangeHandle" ref="dataRef" border v-loading="tableLoading" @select="selectHandles" @select-all="selectAllHandle" @selection-change="selectionChange">
        <!-- 多选 -->
        <el-table-column align="center" type="selection" width="55" v-if="$route.path==='/etaApprovalList'">
        </el-table-column>
        <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'"
              :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>
              <el-button type="text" size="small" @click="Move(row)">移动</el-button>
              <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"
      />
    <!-- 移动弹窗 -->
    <move :isMoveShow.sync="isMoveShow" :moveInfo="moveInfo" @moveConfirm="moveConfirm" @closeMove="closeMove" />

    <!-- 查看账号密码弹窗 -->
    <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 move from './compontents/move.vue';
import applyApprovalDialog from './compontents/applyApprovalDialog.vue';
import{etaTrialColumn,
       adminApprovalList,
       approvedList,
       ApprovalStatus}from './config';
import{etaTrialInterence}from '@/api/modules/crmApi.js';
import { customInterence } from '@/api/api.js'
export default {
  components: { applyApprovalDialog, AddApplyHintDialog, move },
  data() {
    return {
      /* 页面配置 */
      currentPath:'',//当前路由,用于确定columnList,canEdit,tableData
      approvalNum: 0,//还剩多少条待审批
      searchText: "",//搜索框文字
      onlyMine:false,// 是否只是我申请的
      listType: "approved",//非管理员-列表类型,当角色为非管理员时,与当前路由一起确定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,

      //全部全选
      isIndeterminate:false,
      isCheckAll:false,
      isSelectAll:false,//为true时，selectList是剔除的指标，为false时selectList是已选择的指标
      //已选择/已剔除的指标id
      selectList:[],//监听table的select-all select
      choiceIdList:[], //后端返回的选中的列表
      tableDataIds:[],//后端返回的选中的列表id

      isMoveShow:false,//移动弹窗
      moveInfo:{
        type: 1, //1 移动 2 批量移动
        salesArr:[],//销售列表
        selectArr:[],//已选择的id
      },//移动信息
    };
  },
  computed: {
    Role() {
      return localStorage.getItem("Role");
    },
    selectedTotal(){
      if(this.isSelectAll){
        return this.total - (this.selectList ? this.selectList.length : 0)
      }else{
        return this.selectList ? this.selectList.length : 0
      }
    },
  },
  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: {
    getSalesArr() {
      customInterence.getSale().then(res => {
				if(res.Ret === 200) {
          this.moveInfo.salesArr = res.Data.List || [];
				}
			})
    },
    getTableData(type){
      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.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
          if(this.tableData.length>0){
            this.tableDataIds = this.tableData.map(it => it.EtaTrialId)
          }else{
            this.tableDataIds = []
          }
          if(type==='search'){
              //如果是表格筛选项改变导致重新请求数据
              //清除所选
              this.selectList = []
              this.listCheckAllChange(false)
          }else{
              //若不是，数据获取完成后，查询列表全选的值
              //若当页有数据在selectList内，则勾选/剔除
              this.adjustSelection()
          }
        })
     /*  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()
    },

    //勾选/取消勾选表格项
    adjustSelection(){
      if(!this.isSelectAll){
        this.tableData.map(it =>{
              let row = this.selectList.includes(it.EtaTrialId)?it:''
              if(row){
                  this.$nextTick(()=>{
                    this.$refs.dataRef.toggleRowSelection(row,true)
                  })
              }
          })
      }else{
        this.tableData.map(it =>{
          let row = this.selectList.includes(it.EtaTrialId)?'':it
          if(row){
            this.$nextTick(()=>{
              this.$refs.dataRef.toggleRowSelection(row,true)
            })
          }
        })
      }
    },
    //列表全选改变
    listCheckAllChange(value){
        this.selectList = []
        this.isSelectAll = value
        this.$refs.dataRef && this.$refs.dataRef.clearSelection()
        if(value){
            this.$refs.dataRef && this.$refs.dataRef.toggleAllSelection()
        }
    },
    selectionChange(selection){
      // selectAllHandle的触发在selectionChange后面，将selectionChange的逻辑延迟一下
      setTimeout(()=>{
          // 去重
          let duplicateArr = Array.from(new Set(this.selectList))
          //isSelectAll为true时，selectList表示需要剔除的项
          //isSelectAll为false时，selectList表示需要勾选的项
          //全选
          if((duplicateArr.length == this.total && (!this.isSelectAll))|| (duplicateArr.length == 0 && this.isSelectAll)){
              this.isCheckAll = true
              this.isIndeterminate=false
          //全不选
          }else if((duplicateArr.length == 0 && (!this.isSelectAll))|| (duplicateArr.length == this.total && this.isSelectAll)){
              this.isCheckAll = false
              this.isIndeterminate=false
          //半选
          }else{
              this.isCheckAll = false
              this.isIndeterminate=true
          }
      },1)
    },
    selectHandles(selection,row){
        let check = false; 
        if(selection.some(it => it.EtaTrialId == row.EtaTrialId)){
            // 勾选
            if(this.isSelectAll){
                check=false
            }else{
                check=true
            }
        }else{
            // 取消勾选
            if(this.isSelectAll){
                check=true
            }else{
                check=false
            }
        }
        if(check){
          this.selectList.push(row.EtaTrialId)
        }else{
          this.selectList=this.selectList.filter(it => it!=row.EtaTrialId)
        }
    },
    selectAllHandle(selection){
      let check = false; 
      if(selection && selection.length>0){
          // 全选
          if(this.isSelectAll){
              check=false
          }else{
              check=true
          }
      }else{
          // 全不选
          if(this.isSelectAll){
              check=true
          }else{
              check=false
          }
      }
      if(check){
          this.selectList =  [...this.selectList,...this.tableDataIds]
      }else{
          this.selectList = this.selectList.filter(it => !this.tableDataIds.includes(it))
      }
    },
    //将表格数据转换成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()
    },
    moveConfirm(data) {
      console.log(data);
      const {type, value, selectArr} = data
      const currentSellerId = parseInt(value[value.length-1])
      const params = {
        currentSellerId,
        EtaTrialIdList: selectArr,
        IsCheckAll: type === 1 ? false : this.isSelectAll,
        CurrentSellerName: this.findElementByAdminId(this.moveInfo.salesArr, currentSellerId).RealName
      }
      etaTrialInterence.accountTransfer(params).then(res=>{
        if(res.Ret!==200) return
        this.$message.success('移动成功')
        this.getTableData()
        this.isMoveShow = false
      })
    },
    findElementByAdminId(arr, adminId) {
      console.log(arr);
      console.log(adminId);
      adminId = adminId + ''
      for (const element of arr) {
        if (element.AdminId === adminId) {
          return element; // 如果找到匹配的AdminId，直接返回该元素
        }
        if (element.ChildrenList && element.ChildrenList.length > 0) {
          const found = this.findElementByAdminId(element.ChildrenList, adminId); // 递归查找子列表
          if (found) {
            return found; // 如果在子列表中找到了匹配的元素，返回它
          }
        }
      }
      return null; // 如果没有找到匹配的元素，返回null
    },
    closeMove() {
      this.isMoveShow = false
    },
    Move(row) {
      this.moveInfo.type = 1
      this.moveInfo.selectArr = [row.EtaTrialId]
      this.isMoveShow = true
    },
    batchMove() {
      if (this.selectList.length === 0) return this.$message.warning('请至少选择一个客户')
      this.moveInfo.type = 2
      this.moveInfo.selectArr = this.selectList
      this.isMoveShow = true               
    },
    async batchOperate() {
      if(this.getMobileList(this.tableData, this.selectList).length === 0) return this.$message.warning('请至少选择一个客户')
      const res = await etaTrialInterence.applyEnable({
        MobileList:this.getMobileList(this.tableData, this.selectList),
        IsCheckAll:this.isSelectAll,
      })
      if(res.Ret!==200) return 
      this.getTableData()
      this.$message.success('启用成功')
    },
    getMobileList(array1, array2) {
      return array1.filter(element => array2.includes(element.EtaTrialId)).map(element => element.Mobile);
    },
  },
  //如果需要刷新时存listType 用beforeRouteLeave
  mounted(){
    this.currentPath = this.$route.path
    // this.listType = sessionStorage.getItem('etaApprovalListType')||'all'
    // sessionStorage.removeItem('etaApprovalListType')
    this.getTableData()
    this.getSalesArr()
  }
};
</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{
      .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;
        }
      }
      .tips {
        margin: 10px 25px;
        font-family: Arial;
        font-size: 15px;
        font-weight: 400;
        line-height: 17.25px;
        text-align: center;
        color: rgba(153, 153, 153, 1);
      }
      .right-header {
        margin-top: 40px;
      }
    }
    .search-wrap{
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .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>
