<template>
  <div class="classify-en-box">
    <el-card>
      <div class="header" slot="header">
        <div class="type-box">
					<span @click="$emit('typeChange','1')">中文分类</span>
					<span class="act">英文分类</span>
				</div>
        <div>
        <el-button type="primary" size="small" @click="addClassify"
          >添加分类</el-button
        >
        <el-input
          placeholder="分类名称"
          v-model="searchform.key_word"
          clearable
          size="small"
          style="width: 250px"
          @change="getList"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        </div>
      </div>
      <div class="tabs-box">
        <span 
          v-for="item in tabsOpt" 
          :key="item.val"
          :class="item.val==aTab?'active':''"
          @click="handleTabChange(item)"
        >{{item.name}}</span>
      </div>

      <el-table
        :data="tableData"
        v-loading="dataLoading"
        :row-class-name="tableRowClassName"
        element-loading-text="数据加载中..."
        :default-expand-all="isexpand"
        row-key="Id"
        style="border: 1px solid #dcdfe6"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          v-for="item in tableColums"
          :key="item.prop"
          :label="item.label"
          :width="item.widthsty"
          :min-width="item.minwidthsty"
          :prop="item.prop"
          :align="item.align || 'left'"
          :default-expand-all="isexpand"
          row-key="Id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <template slot-scope="{ row }">
            <span v-if="item.prop === 'ClassifyOne'">{{
              row.ischild ? "" : row.ClassifyName
            }}</span>
            <span v-else-if="item.prop === 'ClassifyTwo'">{{
              row.ischild ? row.ClassifyName : ""
            }}</span>

            <div v-else-if="item.prop === 'handle'">
              <span 
                class="editsty"
                v-if="row.ischild" 
                @click="handleShowSetVariety(row)"
              >权限配置</span>
              <span class="editsty" style="margin:0 20px" @click="itemHandle('edit',row)">编辑</span>
              <span class="deletesty" @click="itemHandle('del',row)">删除</span>
            </div>
          </template>
        </el-table-column>
        <div slot="empty" style="padding: 100px 0">
          <img
            src="~@/assets/img/cus_m/nodata.png"
            alt=""
            style="display: block; width: 128px; height: 128px; margin: 0 auto"
          />
          <span>暂无数据</span>
        </div>
      </el-table>

      <el-col :span="24" class="toolbar">
        <m-page
          :page_no="page_no"
          :pageSize="15"
          :total="total"
          @handleCurrentChange="pageChange"
        />
      </el-col>
    </el-card>

    <!-- 分类弹窗 -->
    <m-dialog 
      :title="classifyForm.title" 
      :show.sync="classifyForm.show" 
      width="650px"
    >
      <div style="padding-left: 50px">
        <el-form 
          :model="classifyForm" 
          :rules="formRules" 
          ref="formRef" 
          label-position="left"
          hide-required-asterisk
          label-width="80px">
          <el-form-item prop="type" label="所属模块">
            <el-select 
              v-model="classifyForm.type"
              placeholder="请选择所属模块"
              size="small"
              style="width:400px;"
              @change="FormClassifyChange"
              :disabled="classifyForm.title=='编辑英文分类'"
            >
            <el-option v-for="item in tabsOpt" :key="item.val" :label="item.name" :value="item.val"/>
            </el-select>

          </el-form-item>
          <el-form-item prop="classify_name" label="分类名称">
            <el-input 
              type="text" 
              v-model="classifyForm.classify_name" 
              placeholder="请输入" 
              size="small" 
              style="width:400px;"
            />
          </el-form-item>
          <el-form-item prop="parent_id" label="上级分类">
            <el-select 
              v-model="classifyForm.parent_id"
              placeholder="请选择"
              size="small"
              style="width:400px;"
            >
              <el-option label="无" :value="0"/>
              <el-option v-for="item in classifyparentArr" :key="item.ClassifyName" :label="item.ClassifyName" :value="item.Id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="后台排序" prop="sort">
            <el-input 
              type="number" 
              v-model="classifyForm.sort" 
              placeholder="请输入数字" 
              size="small" 
              style="width:400px;"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" style="margin-top: 20px;">
        <el-button
        @click="cancelClassify"
        style="width: 132px; height: 40px"
        >取消</el-button>
        <el-button
          @click="setClassifyHandle"
          type="primary"
          style="width: 132px; height: 40px"
          >保存</el-button>
      </div>
    </m-dialog>

    <!-- 配置权限 -->
    <el-dialog 
      title="权限配置" 
      :visible.sync="showSetVariety" 
      width="705px"
      append-to-body 
      :close-on-click-modal="false"
    > 
      <div style="padding:10px 40px">
      <reportVarietyEnSet ref="varietyIns" :checked="checkedVariety" v-if="showSetVariety" />
      </div>
      <div style="text-align:center;padding:10px 0 30px 0">
        <el-button type="primary" plain @click="showSetVariety=false">取消</el-button>
        <el-button type="primary" style="margin-left:20px" @click="handleSaveVariety">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as classifyEnInterface from "@/api/modules/classifyEnApi.js";
import mPage from "@/components/mPage.vue";
import mDialog from '@/components/mDialog.vue';
import reportVarietyEnSet from '@/components/reportVarietyEnSet.vue'
export default {
  components: { mPage,mDialog,reportVarietyEnSet },
  watch: {
    'classifyForm.show': {
      handler(newval) {
        newval && this.getClassifyOne();
      }
    }
  },
  data() {
    return {
      searchform: {
        key_word: "",
      },

      dataLoading: false,
      page_no: 1,
      total: 0,
      tableData: [],
      tableColums: [
        {
          label: "一级分类",
          prop: "ClassifyOne",
        },
        {
          label: "二级分类",
          prop: "ClassifyTwo",
        },
        {
          label: "操作",
          prop: "handle",
          align: "center",
        },
      ],
      
      classifyparentArr: [],
      classifyForm: {
        title: '',
        show: false,
        classify_name: '',
        parent_id: 0,
        sort: 1,
        classify_id: '',

        type:0
      },
      formRules: {
        classify_name: [{ required:true,message:'请输入分类名称',trigger:'blur'}],
        parent_id: [{ required:true,message:'请输入',trigger:'blur'}],
        sort: [{ required:true,message:'请输入数字',trigger:'blur'}],
        type: [{ required:true,message:'请选择',trigger:'change'}]
      },

      tabsOpt:[
        {
          name:'英文研报',
          val:0
        },
        {
          name:'线上路演',
          val:1
        }
      ],
      aTab:0,

      showSetVariety:false,
      checkedVariety:[],
      activeItem:{},//当前编辑权限的分类
    };
  },

  methods: {
    handleShowSetVariety(item){
      this.activeItem=item
      this.checkedVariety=item.EnPermissions||[]
      this.showSetVariety=true
    },
    handleSaveVariety(){

        let params={
          ClassifyId:this.activeItem.Id,
          EnPermissions:this.$refs.varietyIns.checkedItems||[]
        }
        // console.log(params);
        classifyEnInterface.setClassifyVariety(params).then(res=>{
          if(res.Ret===200){
            this.$message.success('设置成功')
            this.getList();
            this.showSetVariety=false
          }
        })
      },

    getList() {
      //获取列表
      this.dataLoading = true;
      let params = {
        CurrentIndex: this.page_no,
        PageSize: 15,
        KeyWord: this.searchform.key_word,
        ClassifyType:this.aTab
      };
      classifyEnInterface.classifyList(params).then(res => {
        this.dataLoading = false;
        if (res.Ret === 200) {
          this.tableData = res.Data.List || [];
          this.total = parseInt(res.Data.Paging.Totals);
          this.tableData.forEach((item, index) => {
            if (item.Child) {
              // item.hasChildren=true;
              let childnode = JSON.parse(JSON.stringify(item.Child));
              childnode.forEach((itemchild, i) => {
                itemchild.ischild = true;
              });
              item.children = childnode;
            }
          });
        }
      });
    },

    addClassify() {
      this.classifyForm = {
        title: '新增英文分类',
        show: true,
        classify_name: '',
        parent_id: 0,
        sort: 1,
        type:0
      }
    },

    /* 获取一级分类 */
    getClassifyOne() {
      classifyEnInterface.classifyOne({ CurrentIndex: 1, PageSize: 9999,ClassifyType:this.classifyForm.type })
        .then(res => {
          if(res.Ret !== 200) return

          this.classifyparentArr=[];
					res.Data.List && res.Data.List.forEach((item,i)=>{
							item.Id=parseInt(item.Id);

							if(!item.Child) this.classifyparentArr.push(item);
					});
        })
    },

    /* 操作 */
    itemHandle(key,row) {
      const keyMap = {
        'edit': this.editHandle,
        'del': this.delHandle
      }

      keyMap[key](row)
    },

    editHandle({ClassifyName,Id,ParentId,Sort,ClassifyType}) {
      this.classifyForm = {
        title: '编辑英文分类',
        show: true,
        classify_name: ClassifyName,
        parent_id: ParentId,
        sort: Sort,
        classify_id: Id,
        type:ClassifyType
      }
    },

    delHandle({Id,ParentId}) {

      this.$confirm('确认删除吗?','提示',{type:'warning'}).then(() => {
				classifyEnInterface.classifyDel({ClassifyId:Id,ParentId}).then(res =>{
						if( res.Ret!==200 ) return
            
            this.$message.success(res.Msg);
            this.getList();
					});
			}).catch(() => {});
    },

    /* 日期改变 */
    pageChange(page) {
      this.page_no = page;

      this.getList();
    },

    /* 保存分类 */
    async setClassifyHandle() {
      await this.$refs.formRef.validate();

      const { classify_name,parent_id,sort,classify_id } = this.classifyForm;
      let params = {
        ClassifyName: classify_name,
        ParentId: parent_id,
        Sort: sort
      }

      const { Ret,Msg } = classify_id 
        ? await classifyEnInterface.classifyEdit({...params,ClassifyId: classify_id}) 
        : await classifyEnInterface.classifyAdd({...params,ClassifyType:this.classifyForm.type})

      if(Ret !== 200) return
      this.$message.success(Msg)
      this.cancelClassify();
      this.getList();
    },

    /* 取消 */
    cancelClassify() {
      this.$refs.formRef.resetFields();
      this.classifyForm.show = false;
    },

    //切换分类
    handleTabChange(item){
      this.aTab=item.val
      this.page_no=1
      this.searchform.key_word=''
      this.getList()
    },

    //新增分类时切换分类
    FormClassifyChange(){
      this.classifyForm.parent_id=0
      this.getClassifyOne()
    }
  },

  mounted() {
    this.getList();
  },
};
</script>

<style lang="scss" scoped>
.classify-en-box {
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .type-box{
				span{
					cursor: pointer;
					display: inline-block;
					margin-right: 50px;
					font-size: 18px;
					padding-bottom: 10px;
				}
				.act{
					color: #409EFF;
					border-bottom: 2px solid #409EFF;
				}
		}
  }
  .tabs-box{
    margin-bottom: 20px;
    width: 160px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    overflow: hidden;
    span{
      display: inline-block;
      width: 80px;
      line-height: 40px;
      color: #666;
      cursor: pointer;
      text-align: center;
    }
    .active{
      color: #fff;
      background-color: #409EFF;
    }
  }
}
</style>
