<template>
  <div class="taglib-page-wrap">
    <div class="top-wrap">
      <div class="switch-tab">
        <div class="tab-item" :class="{'active':tableName==='tag'}"
         @click="changTable('tag')">
          标签列表
        </div>
        <div class="tab-item" :class="{'active':tableName==='classify'}"
        @click="changTable('classify')">
          标签分类列表
        </div>
      </div>
      <div class="tool-wrap" :style="{'justify-content':tableName==='tag'?'space-between':'flex-end'}">
        <template v-if="tableName==='classify'">
          <el-button  type="primary" size="medium" @click="addTag">添加标签分类</el-button>
        </template>
        <template v-else>
          <el-button type="primary" size="medium" @click="addTag">添加标签</el-button>
          <el-cascader style="width:200px;" placeholder="请选择标签分类"
                      :options="selectTagTree" v-model="searchClassify" @change="handleSearchChange('select')" clearable></el-cascader>
          <el-input  style="width:210px;" placeholder="标签名称"  prefix-icon="el-icon-search" clearable
                     v-model="searchInput" @input="handleSearchChange('input')"
          ></el-input>
         </template>
      </div>
    </div>
    <div class="tag-table">
      <el-table :data="tableData" border v-loading="tableLoading">
        <el-table-column v-for="item in tableColumn" :key="item.key"
        :prop="item.key" :label="item.label" align="center">
          <template slot-scope="{row}">
            <span v-if="item.key==='state'" :style="{'color':row.state===1?'#606266':'rgb(209, 67, 58)'}">{{row.state===1?'启用':'禁用'}}</span>
            <span v-else-if="item.key==='RelatVariety'">
              {{row.chart_permission_classify_name}}/{{row.chart_permission_name}}
            </span>
            <span v-else>{{row[item.key]}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot="header" slot-scope="{}">
            <span>操作</span>
            <el-tooltip
              effect="dark"
              placement="top-start"
              :content="`禁用后将关闭该标签${tableName==='tag'?'':'分类'}，不清除历史数据`"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </template> 
          <template slot-scope="{ row }">
            <span @click="editTag(row)"
                  style="color:rgb(64, 153, 239);cursor: pointer;margin-right:10px;"
            >编辑</span>
            <span @click="handleChangeTagStatus(row)"
                  style="cursor: pointer"
                  :style="{color:row.state===1?'rgb(209, 67, 58)':'rgb(64, 153, 239)'}"
            >{{row.state===1?'禁用':'启用'}}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination layout="total,prev,pager,next,jumper" background :current-page="page_no"
        @current-change="handleCurrentChange" :page-size="pageSize" :total="total"
        style="text-align: end; margin-top: 20px">
      </el-pagination>
    </div>
    <!-- 添加/编辑标签弹窗 -->
     <el-dialog v-if="tagDialogShow" :visible.sync="tagDialogShow" :close-on-click-modal="false" :modal-append-to-body="false"
      @close="handleDialog('close')" width="689px" v-dialogDrag center>
      <div slot="title" style="display: flex; alignitems: center">
        <span style="fontsize: 16px">{{tagForm.tag_name?'编辑':'添加'}}标签</span>
      </div>
      <div class="dialog-container">
        <div class="input-item">
          标签名称：<el-input  placeholder="请输入标签名称" v-model="tagForm.tag_name" required ></el-input>
        </div>
        <div class="input-item">
          标签分类：<el-cascader placeholder="请选择标签分类" v-model="tagForm.variety_classify_id"
                                :options="tagTreeOptions"></el-cascader>
        </div>
        <div class="input-item">
          关联品种：<el-cascader placeholder="请选择关联品种" v-model="tagForm.chart_permission_id"
                                :show-all-levels="false" :props="{emitPath:false}"  :options="permissionOptions"></el-cascader>
        </div>
      </div>
      <div slot="footer" class="foot-container">
        <el-button type="primary" @click="handleChangeTag">确 定</el-button>
        <el-button @click="handleDialog('close')">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加/编辑标签分类弹窗 -->
    <el-dialog v-if="classifyDialogShow" :visible.sync="classifyDialogShow" :close-on-click-modal="false" :modal-append-to-body="false"
      @close="handleDialog('close')" width="689px" v-dialogDrag center>
      <div slot="title" style="display: flex; alignitems: center">
        <span style="fontsize: 16px">{{tagForm.classify_name?'编辑':'添加'}}标签分类</span>
      </div>
      <div class="dialog-container">
        <div class="input-item">
          标签分类名称：<el-input  placeholder="请输入标签分类名称" v-model="tagForm.classify_name" required ></el-input>
        </div>
      </div>
      <div slot="footer" class="foot-container">
        <el-button type="primary" @click="handleChangeTag">确 定</el-button>
        <el-button @click="handleDialog('close')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import taglibApi from "@/api/modules/taglibApi.js";
import {departInterence,customInterence} from '@/api/api.js';
export default {
  data() {
    return {
      tableColumn:[],//表格列,值为tagTableColumn或classifyTableColumn
      tableData:[],//表格数据
      tableLoading:false,//表格的loading
      permissionOptions:[],//品种筛选框数据
      tagForm:{},//新增/编辑 标签,标签分类数据
      tableName:'',//当前展示的表格名
      page_no:1,//分页相关
      pageSize:10,
      total:2,
      searchInput:'',//标签名称筛选
      tagTreeOptions:[],//标签分类筛选
      selectTagTree:[],
      searchClassify:0,//标签分类筛选的值
      tagDialogShow:false,//弹窗显示/隐藏相关
      classifyDialogShow:false,
      tagTableColumn:[
         {
          label: "标签名称",
          key: "tag_name",
        },
        {
          label: "标签分类",
          key: "variety_classify_name",
        },
        {
          label: "关联品种",
          key: "RelatVariety",
        },
        {
          label: "更新时间",
          key: "modify_time",
        },
        {
          label: "状态",
          key: "state",
        }
      ],
      classifyTableColumn:[
        {
          label: "标签分类名称",
          key: "classify_name",
        },
        {
          label: "更新时间",
          key: "modify_time",
        },
        {
          label: "状态",
          key: "state",
        }
      ]
    };
  },
  methods: {
    //新增 标签/标签分类
    addTag(){
      this.tagForm = {}
      //打开对应弹窗
      this.handleDialog('open')
    },
    //编辑 标签/标签分类
    editTag(row){
      this.tagForm = row
      this.handleDialog('open')
    },
    //处理 新增/编辑标签,标签分类
    async handleChangeTag(){
      const {status,hintText} = this.checkTagForm()
      if(!status){
        this.$message.warning(hintText)
        return
      }
      console.log(this.tagForm)
      //调接口
      let res = null
      if(this.tableName==='tag'){
        res = await this.changeTag()
      }else{
        res = await this.changeClassify()
      }
      if(res.Ret!==200){
        //this.$message.error(res.ErrMsg)
        return 
      }else{
        let isEdit = this.tableName==='tag'&&this.tagForm.variety_tag_id||this.tableName==='classify'&&this.tagForm.variety_classify_id
        this.$message.success(`${isEdit?'编辑':'新增'}成功`)
      }
      //then
      this.tagForm = {}
      this.handleDialog('close')
      //如果更新的是标签分类,则需要重新获取一次标签树
      this.getTagTree()
      this.getAllClassifyList()
      this.page_no = 1
      this.getTableList()
    },
    changeTag(){
      const {variety_tag_id,variety_classify_id,tag_name,chart_permission_id}=this.tagForm
      const v_c_id = Array.isArray(variety_classify_id)?variety_classify_id[0]:variety_classify_id
      const c_p_id = Array.isArray(chart_permission_id)?chart_permission_id[chart_permission_id.length-1]:chart_permission_id
      return taglibApi.modifyTag({
        variety_tag_id:variety_tag_id?variety_tag_id:0,
        variety_classify_id:v_c_id,
        tag_name,
        chart_permission_id:c_p_id
      })
    },
    changeClassify(){
      const {variety_classify_id,classify_name} = this.tagForm
      return taglibApi.modifyClassify({
        variety_classify_id:variety_classify_id?variety_classify_id:0,
        classify_name
      })
    },
    //处理 启用/禁用标签,标签分类
    async handleChangeTagStatus(row){
      //调接口
      let res = null
      if(this.tableName==='tag'){
        res = await this.changeTagStatus(row)
      }else{
        res = await this.changeClassifyStatus(row)
      }
      if(res.Ret!==200){
        //this.$message.error(res.ErrMsg)
        return 
      }else{
        this.$message.success('操作成功')
      }
      //then
      this.getTableList()
    },
    changeTagStatus({variety_tag_id,state}){
      return taglibApi.setTagStatus({
        variety_tag_id,
        state:state===0?1:0
      })
    },
    changeClassifyStatus({variety_classify_id,state}){
      return taglibApi.setClassifyState({
        variety_classify_id,
        state:state===0?1:0
      })
    },
    //切换表格
    changTable(tableName){
      this.tableName = tableName
      this.tableColumn = this.tableName==='tag'?this.tagTableColumn:this.classifyTableColumn
      //重置分页
      this.page_no = 1
      this.getTableList()
    },
    handleSearchChange(type){
      if(type==='input'){
        this.searchClassify = 0
      }else{
        this.searchInput=''
      }
      this.page_no = 1
      this.getTagList()
    },
    //获取表格数据
    getTableList(){
      this.tableLoading = true
      if(this.tableName==='tag'){
        this.getTagList()
      }else{
        this.getClassifyList()
      }
    },
    async getTagList(){
      let searchObj = {}
      if(this.searchClassify!==0){
        searchObj.ClassifyId = this.searchClassify[0]
      }
      const res = await taglibApi.getTagList({...{
        PageSize:this.pageSize,
        CurrentIndex:this.page_no,
        Keywords:this.searchInput
      },...searchObj})
      if(res.Ret===200){
        const {Paging,List} = res.Data
        this.page_no = Paging.CurrentIndex
        this.total = Paging.Totals
        this.tableData = List
        this.tableLoading = false
      }
    },
    async getClassifyList(){
      const res = await taglibApi.getClassifyList({
        PageSize:this.pageSize,
        CurrentIndex:this.page_no,
      })
      if(res.Ret===200){
        const {Paging,List} = res.Data
        this.page_no = Paging.CurrentIndex
        this.total = Paging.Totals
        this.tableData = List
        this.tableLoading = false
      }
    },
    //获取品种数据
    async getPermissionList(){
      const res = await customInterence.authList({CompanyType:'ficc'})
      if(res.Ret===200){
        let arr=res.Data.List||[]
        this.permissionOptions=arr.map(item => {
            let obj={}
            obj.value=item.ClassifyName
            obj.label=item.ClassifyName
            obj.children=item.Items.map(_item=>{
                return {value:_item.ChartPermissionId,label:_item.PermissionName}
            })
            return obj
        }).filter(item=>item.value!='市场策略');
      } 
    },
    //获取标签树数据
    async getTagTree(){
      const res = await departInterence.getTagTree()
      if(res.Ret === 200){
        let arr=res.Data||[]
        this.tagTreeOptions=arr.map(item => {
            let obj={}
            obj.value=item.classify_id
            obj.label=item.classify_name
            return obj
        })
      }
    },
    //获取标签列表数据,PageSize:100,作为标签分类筛选框的数据
    async getAllClassifyList(){
      const res = await taglibApi.getClassifyList({
        PageSize:100,
        CurrentIndex:1,
      })
      if(res.Ret===200){
        const {List} = res.Data
        this.selectTagTree = List.map(item=>{
          let obj={}
          obj.value = item.variety_classify_id
          obj.label = item.classify_name
          return obj
        })
      }
    },
    //分页
    handleCurrentChange(page){
      this.page_no = page
      this.getTableList()
    },
    //控制弹窗
    handleDialog(type){
      if(this.tableName==='tag'){
        this.tagDialogShow = type==='open'?true:false
      }else{
        this.classifyDialogShow = type==='open'?true:false
      }
      if(type==='close'){
        this.tagForm={}
      }
    },
    //校验 标签,标签分类表单
    checkTagForm(){
     const tagCheck = [
       {key:'tag_name',name:'标签名称',handle:'输入'},
       {key:'variety_classify_id',name:'标签分类',handle:'选择'},
       {key:'chart_permission_id',name:'关联品种',handle:'选择'}
     ] 
     const classifyCheck = [{key:'classify_name',name:'标签分类',handle:'输入'}]
     const checkArr = this.tableName==='tag'?tagCheck:classifyCheck
     for(let i of checkArr){
       if(!this.tagForm[i.key]){
         return {status:false,hintText:'请'+i.handle+i.name}
       }
     }
     return {status:true,hintText:''}
    }
  },
  mounted(){
    //获取标签树
    this.getTagTree()
    this.getAllClassifyList()
    //获取品种列表
    this.getPermissionList()
    //默认显示标签列表
    this.changTable('tag')
  }
};
</script>
<style lang="scss">
.taglib-page-wrap{
  .dialog-container{
    .input-item{
      .el-cascader{
        .el-input{
          width: 100%;
        }
      }
    }
  }
}
</style>
<style scoped lang="scss">
.taglib-page-wrap{
  background-color: #fff;
  box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  padding: 30px 20px;
  min-height: calc(100vh - 120px);
  box-sizing: border-box;
  .top-wrap{
    width:100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .switch-tab{
      /* width:200px; */
      display: flex;
      .tab-item{
        font-size: 16px;
        margin-right: 30px;
        height:24px;
        line-height: 24px;
        padding-bottom: 2px;
        cursor: pointer;
        &.active{
          color: #409EFF;
          border-bottom: 2px solid #409EFF;
        }
      }
    }
    .tool-wrap{
      display: flex;
      width:600px;
      height: 40px;
      justify-content: space-between;
    }
  }
  .dialog-container{
    display: flex;
    flex-direction: column;
    align-items: center;
    .input-item{
      width: 350px;
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      .el-input,.el-cascader{
        flex: 1;
      }
    }
  }
}
</style>
