<template>
  <div class="container-userapplication">
    <div class="userapplication-top">
      <div class="top-tabs">
        <!-- <span v-for="item in Tabs" :key="item.name" @click="handleTabsClick(item)" :class="activeName == item.type ? 'active' : ''">
          {{ item.name }}
        </span> -->
        <el-radio-group v-model="activeItem" @input="handleTabsClick(activeItem)">
            <el-radio-button :label="item" v-for="item in Tabs" :key="item.name">{{item.name}}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <el-card style="margin-top: 20px">
        <div class="export-select">
        <!-- <a style="width:80px; margin-right: 20px" :href="exportUrl" download v-if="Tabs.length>1">
          <el-button type="primary" style="width: 100%"  >导出</el-button>
        </a> -->
        <date-picker 
            v-model="date_range" 
            type="date" 
            range
            value-type="format"
            :placeholder="`请选择${activeName===1?'提交':activeName===2?'申请':'发送'}时间`"
            @change="changeQuery">
        </date-picker>
        <el-select v-if="activeName == 1" v-model="custom_apply_type" placeholder="请选择申请类型" style="width: 160px;" clearable @change="changeQuery">
          <el-option v-for="item in applyArr" :key="item.name" :label="item.name" :value="item.name"> </el-option>
        </el-select>
        <el-select v-if="activeName == 1" v-model="custom_type" placeholder="请选择用户状态" style="width: 200px;" clearable multiple @change="changeQuery">
          <el-option v-for="item in statusArr" :key="item.name" :label="item.name" :value="item.name"> </el-option>
        </el-select>
        <el-select v-model="group_type" placeholder="请选择分组" style="width: 160px;" clearable @change="changeQuery">
          <el-option v-for="item in groupArr" :key="item.name" :label="item.name" :value="item.name"> </el-option>
        </el-select>
        <el-input placeholder="姓名/手机号/邮箱/公司名称" v-model="search_txt" clearable style="max-width: 240px" @input="changeQuery">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
      <el-table :data="tableData" v-loading="tableLoading" element-loading-text="数据加载中..." border>
        <el-table-column v-for="item in tableColums" :key="item.label" :label="item.label" :width="item.widthsty" :min-width="item.minwidthsty" align="center">
          <template slot-scope="{ row }">
            <div v-if="item.key == 'CompanyName'">
              <span
                style="color: #409eff; cursor: pointer"
                v-if="row.CompanyId > 1"
                @click="
                  $router.push({
                    path: '/RaiDetail',
                    query: {
                      id: row.CompanyId,
                    },
                  })
                "
                >{{ row.UserCompanyName||row.CompanyName }}</span
              >
              <span v-else>{{ row.UserCompanyName||row.CompanyName }}</span>
            </div>
            <span v-else @click="handleRowClick(row,item.key)" :style="handleRowStyle(item.key)">{{handleRowContent(row,item.key)}}</span>
            <!-- <span @click="lookReport(row)" style="color: #409eff; cursor: pointer" v-else-if="item.key == 'ViewTotal'">{{ row[item.key] || 0 }}</span>
            <span v-else-if="['LastTime','LastViewTimeStr'].includes(item.key)">{{$moment(row[item.key]).format('YYYY-MM-DD HH:mm:ss')}}</span>
            <span v-else>{{ row[item.key] }}</span> -->
          </template>
        </el-table-column>
        <el-table-column label="分组" align="center">
            <template slot-scope="{ row }">
                <span>{{row.MarkGroup}}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <div v-if="activeName == 1">
             <!--  <span class="editsty" v-if="row.OpStatus === 0 && row.IsMove === 0&&!(row.Status==='潜在用户'||row.Status==='流失')" @click="dealHandle(row)">标记处理</span> -->
              <span class="editsty" v-if="row.OpStatus === 0 && row.IsMove === 0" @click="handleChooseGroup(row)">标记</span>
            </div>
            <div v-else>
              <!-- <span class="editsty" v-if="row.Status==='待处理'" @click="dealHandle(row)">标记处理</span> -->
              <span class="editsty" v-if="row.Status==='待处理'" @click="handleChooseGroup(row)">标记</span>
            </div>
            <span class="editsty" v-if="activeName == 1&&row.IsMove === 0" @click="moveHandle(row)">移动</span>
            <!-- <span class="editsty" style="color:#ff0000" v-if="row.DelBtn" @click="delHandle(row)">删除</span> -->
          </template>
        </el-table-column>
        <div slot="empty" style="padding: 20px 0">
          <img src="~@/assets/img/data_m/table_no.png" alt="" style="display: block; width: 135px; height: 90px; margin: 0 auto" />
          <span>暂无数据</span>
        </div>
      </el-table>
      <el-col :span="24" class="toolbar">
        <m-page :total="total" :page_no="page_no" :pageSize="10" @handleCurrentChange="handleCurrentChange" />
      </el-col>
    </el-card>
    <!-- 阅读报告弹窗 -->
    <Readia :readId="readId" :lookRead="isRead" :title="readTit" @cancelRead="cancelRead"> </Readia>
    <!-- 处理弹窗 -->
    <intervewDia :isShowDia.sync="isShowDia" :item="dealObj" v-if="isShowDia" :activeName="activeName"/>
    <!-- 移动弹窗 -->
    <moveCustomDia :isShow.sync="isShowMoveDia" :item="dealObj" v-if="isShowMoveDia" />
    <!-- 标记分组弹窗 -->
    <el-dialog
        v-dialogDrag 
        :visible.sync="isChooseGroupDialogShow"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        title="标记" width="480px" center
        @close="isChooseGroupDialogShow=false">
        <div class="dialog-container">
            <div class="select" style="display:flex;align-items: center;">
                <span>分组：</span>
                <el-select v-model="choosed_group" placeholder="请选择分组" style="flex:1;margin-left: 10px;">
                    <el-option v-for="item in groupArr" :key="item.name" :label="item.name" :value="item.name"> </el-option>
                </el-select>
            </div>
        </div>
        <div style="display:flex;justify-content:center;margin:20px 0;">
            <el-button type="primary" style="width:80px;marginRight:24px;" @click="chooseGroup">保存</el-button>
            <el-button type="primary" plain style="width:80px;" @click="isChooseGroupDialogShow=false">取消</el-button>
        </div>
	</el-dialog>
  </div>
</template>

<script>
import { ficcManageInterface, customInterence } from "@/api/api.js";
import mPage from "@/components/mPage.vue";
import { tableColums } from "./userTableColums";
import Readia from "../custom_manage/compontents/ReadDialog.vue";
import intervewDia from "./apply/components/interviewDia.vue";
import moveCustomDia from "./apply/components/moveCustomDia.vue";
export default {
  name: "userApplication",
  components: { mPage, Readia, intervewDia, moveCustomDia },
  props: {},
  data() {
    return {
      tableLoading: false,
      tableData: [],
      tableColums: [],
      activeName: 1,
      activeItem: { name: "弘则研报", type: 1 },
      total: 0,
      page_no: 1,
      pageSize: 10,
      getTabs: [
        { name: "弘则研报", type: 1 },
        { name: "中文官网", type: 2 },
        { name: "英文官网", type: 3 },
      ],
      statusArr: [
        { name: "潜在用户", value: 1 },
        /* { name: "权益用户", value: 2 }, */
        { name: "流失", value: 3 },
        { name: "冻结", value: 4 },
        {name:'试用暂停',value:5}
      ],
      groupArr:[
        {name:"楼颖丹组",value:"楼颖丹组"},
        {name:"时代组",value:"时代组"},
        {name:"岳梦琳组",value:"岳梦琳组"},
        {name:"权益组",value:"权益组"}
        ],
      choosed_group:'',
      choosed_row:null,
      custom_type:[],
      custom_apply_type:'',//申请类型
      date_range:[],
      group_type:'',
      applyArr:[
        {name:'已申请',value:'已申请'},
        {name:'未申请',value:'未申请'},
      ],
      search_txt:'',
      isRead: false, //报告列表弹窗
      readTit: "阅读报告列表",
      readId: "",
      dealObj: {},
      isShowDia: false, //处理弹窗
      isShowMoveDia: false, //移动弹窗
      isChooseGroupDialogShow:false
    };
  },
  computed: {
     exportUrl() {
      let url = process.env.API_ROOT ;
      let param_token = localStorage.getItem("auth") || "";
      let sourceType = this.activeName===2?'中文官网':'英文官网'
      const recodeUrl = `/yb/apply_record/listV2/export?States=${this.search_type}&ApplyStatus=${this.custom_apply_type}&KeyWord=${this.search_txt}&${param_token}`
      const official = `/custom/official/user/list/export?SourceType=${sourceType}&KeyWord=${this.search_txt}&${param_token}`
      url+=this.activeName===1?recodeUrl:official
      return url;
    },//导出url
    Tabs(){
      //判断Role，为销售时不显示后面两个
      let roleType = localStorage.getItem('Role')
      if(!['ficc_admin','admin'].includes(roleType)){
        return [this.getTabs[0]]
      }else{
        return this.getTabs
      }
    },//tabs数组,根据Role决定是否显示后两个
    search_type(){
      return this.custom_type.join(',')
    },//筛选客户的类型,可多选
  },
  watch: {},
  created() {},
  mounted() {
    this.tableColums = tableColums(1);
    this.getTableData();
  },
  methods: {
    changeQuery(){
        this.page_no = 1
        this.getTableData()
    },
    /* 获取表格数据 */
    async getTableData() {
      this.tableLoading = true;
      const res =
        this.activeName == 1
          ? await ficcManageInterface.applyRecordListV2({
              PageSize: this.pageSize,
              CurrentIndex: this.page_no,
              KeyWord: this.search_txt,
              States: this.search_type,
              ApplyStatus:this.custom_apply_type,
              MarkGroup:this.group_type,
              StartDate:this.date_range[0],
              EndDate:this.date_range[1],
            })
          : await customInterence.trialList({
              PageSize: this.pageSize,
              CurrentIndex: this.page_no,
              SourceType: this.activeName == 2 ? "中文官网" : this.activeName == 3 ? "英文官网" : "",
              KeyWord: this.search_txt,
              MarkGroup:this.group_type,
              StartDate:this.date_range[0],
              EndDate:this.date_range[1],
            });

      if (res.Ret === 200) {
        this.tableData = res.Data.List || [];
        this.total = res.Data.Paging.Totals;
        this.tableLoading = false;
      }
    },
    /* top的点击事件 */
    handleTabsClick(item) {
      if (this.activeName != item.type) {
        this.activeName = item.type;
        this.tableColums = tableColums(this.activeName);
      }
      //重置筛选项
      this.search_txt=''
      this.custom_type=[]
      this.custom_apply_type=[]
      this.date_range=[]
      this.group_type=''

      this.page_no = 1;
      this.getTableData();
    },
    /* 表格行的点击事件 */
    handleRowClick(row,key){
      if(key==='ViewTotal'){
        this.lookReport(row)
      }
    },
    /* 表格行的样式 */
    handleRowStyle(key){
      const style = {
        'ViewTotal':"color: #409eff; cursor: pointer"
      }
      return style[key]?style[key]:""
    },
    /* 表格行的数据处理 */
    handleRowContent(row,key){
      if(['LastTime','LastViewTimeStr'].includes(key)){
        
        return row[key]&&row[key].length>0?this.$moment(row[key]).format('YYYY-MM-DD HH:mm:ss'):""
      }else{
        return row[key]
      }
    },
    // 页码改变事件
    handleCurrentChange(page, index) {
      this.page_no = page;
      this.getTableData();
    },
    /* 查看阅读报告列表 */
    lookReport(item) {
      console.log(item);
      this.readId = item.UserId;
      this.readTit = item.RealName + "阅读报告列表";
      this.isRead = true;
    },
    /* 关闭阅读报告弹窗 */
    cancelRead() {
        this.readTit = '阅读报告列表';
        this.isRead = false;
    },
    // 移动
    moveHandle(item) {
      this.dealObj = item;
      this.isShowMoveDia = true;
    },
    // 标记处理
    dealHandle(item) {
      this.dealObj = item;
      this.isShowDia = true;
    },
    //删除
    delHandle(item){
      this.$confirm('是否删除该申请记录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ficcManageInterface.delPotentialUser({UserId:Number(item.UserId)}).then(res=>{
          if(res.Ret===200){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getTableData();
          }
        })
      }).catch(() => {
                  
      });
    },
    //打开标记分组弹窗
    handleChooseGroup(row){
        this.choosed_row = row
        this.choosed_group=''
        this.isChooseGroupDialogShow = true
    },
    //标记分组
    async chooseGroup(){
        if(!this.choosed_group){
            this.$message.warning('请选择分组')
            return 
        }
        const {ApplyRecordId,UserId,Id} = this.choosed_row
        //请求接口
        const res = this.activeName===1?await customInterence.markApplyUser({
            ApplyRecordId,UserId,GroupName:this.choosed_group
        }):await customInterence.markOfficialUser({Id,GroupName:this.choosed_group})

        if(res.Ret!==200) return 
        this.$message.success('标记分组成功')
        this.isChooseGroupDialogShow = false
        this.choosed_group=''
        this.getTableData()
        
    }
  },
};
</script>
<style lang="scss">
.container-userapplication{
    .mx-datepicker{
        width:200px !important;
    }
}
</style>
<style scoped lang="scss">
.container-userapplication {
    min-width: 1500px;
  .userapplication-top {
    display:flex;
    align-items:center;
    justify-content: space-between;
    border: 1px solid #ECECEC;
		padding: 20px 30px;
		background: #fff;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
  }
  .top-tabs {
    display: flex;
    .active {
      background-color: #409eff;
      color: #fff;
    }
    span {
      display: inline-block;
      box-sizing: border-box;
      padding: 0 24px;
      line-height: 38px;
      height: 40px;
      background: #ecf5ff;
      border: 1px solid #b3d8ff;
      opacity: 1;
      font-weight: 500;
      font-size: 16px;
      color: #409eff;
      border-radius: 4px;
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .export-select {
    display: flex;
    flex: 1;
    justify-content: flex-start;
    align-items: flex-start;
    gap: 10px;
    margin-bottom: 20px;
    .el-input{
        margin-left: auto;
    }
  }
}
</style>
