<template>
  <div class="report-variety-page">
    <div class="top-wrap">
      <el-input
        placeholder="分类名称"
        v-model="searchVal"
        style="max-width: 262px"
        @change="getlist"
        clearable
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
    </div>
    <div class="content-box">
      <el-tree
        :data="list"
        node-key="Id"
        :props="{
          label: 'ClassifyName',
          children: 'Child',
        }"
        check-strictly
        empty-text="暂无数据"
        indent="76"
      >
        <div class="classify-item-wrap" slot-scope="{ node, data }">
          <div>
            <span :class="['tag', data.Enabled==1?'open':'close']">{{data.Enabled==1?'启用':'禁用'}}</span>
            <span>{{ data.ClassifyName }}</span>
          </div>

          <div class="opt-box">
            <span class="editsty" v-if="!data.Child" @click="chapterSetting(data)">章节设置</span>
            <span
              style="cursor: pointer; color: #409eff"
              @click.stop="handleShowEdit(data)"
              >小程序配置</span
            >
          </div>
        </div>
      </el-tree>
    </div>

    <!-- 分类弹窗 -->
    <m-dialog title="小程序配置" :show.sync="aeForm.show" width="650px">
      <div style="padding-left: 50px">
        <el-form
          :model="aeForm"
          :rules="aerules"
          ref="aeForm"
          label-position="left"
          hide-required-asterisk
          label-width="100px"
        >
          <el-form-item
            prop="showType"
            label="列表页展示"
            v-if="aeForm.parent_id == 0"
          >
            <el-select
              v-model="aeForm.showType"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option label="列表" :value="1"></el-option>
              <!-- <el-option label="专栏" :value="2"></el-option>  -->
              <el-option label="品种" :value="3"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item
            prop="showType"
            label="详情页展示"
            v-if="aeForm.isLastLevel"
          >
            <el-select
              v-model="aeForm.reportDetailShowType"
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option label="拼接" :value="1"></el-option>
              <el-option label="目录" :value="2"></el-option>
            </el-select>
          </el-form-item>

          <!-- 一级目录子目录 -->
          <el-form-item
            label="子目录"
            v-if="aeForm.parent_id == 0 && aeForm.showType == 1"
          >
            <draggable v-model="ClassifyMenuList" animation="300">
              <div
                style="display: inline-block; margin-right: 5px"
                v-for="(item, index) in ClassifyMenuList"
                :key="item"
              >
                <el-input
                  v-if="item.inputVisible"
                  v-model="item.MenuName"
                  ref="itemINput"
                  size="small"
                  style="width: 90px"
                  :autofocus="true"
                  @keyup.enter.native="item.inputVisible = false"
                  @blur="item.inputVisible = false"
                ></el-input>
                <el-tag
                  v-else
                  closable
                  :disable-transitions="false"
                  @click="showInput(index)"
                  @close="handleClose(index)"
                >
                  {{ item.MenuName }}
                </el-tag>
              </div>
            </draggable>
            <div>
              <el-input
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
                style="width: 90px"
              >
              </el-input>
              <el-button v-else size="small" @click="showInput(-1)"
                >+ 点击新增</el-button
              >
            </div>
          </el-form-item>
          <!-- 二级目录子目录 -->
          <el-form-item label="子目录" v-if="aeForm.parent_id != 0&&selectMenuOpt.length>0">
            <el-select
              v-model="aeForm.ClassifyMenuId"
              clearable
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option
                :label="item.MenuName"
                :value="item.MenuId"
                v-for="item in selectMenuOpt"
                :key="item.MenuId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="FICC页icon"
            v-if="aeForm.parent_id == 0"
            prop="YbFiccIcon"
          >
            <input
              type="file"
              size="small"
              name="file"
              @change="fileSelected(6)"
              id="file6"
              class="true-file"
              style="display: none"
            />
            <el-input
              readonly
              type="text"
              v-model="aeForm.YbFiccIcon"
              placeholder="上传FICC页icon"
              size="medium"
              style="width: 400px"
            >
              <el-button
                slot="append"
                type="primary"
                size="mini"
                @click.native="clickinput(6)"
                >选择图片</el-button
              >
            </el-input>
          </el-form-item>
          <el-form-item
            label="报告合集配图"
            v-if="aeForm.parent_id == 0 && aeForm.showType !== 2"
            prop="YbRightBanner"
          >
            <input
              type="file"
              size="small"
              name="file"
              @change="fileSelected(11)"
              id="file11"
              class="true-file"
              style="display: none"
            />
            <el-input
              readonly
              type="text"
              v-model="aeForm.YbRightBanner"
              placeholder="上传报告合集配图"
              size="medium"
              style="width: 400px"
            >
              <el-button
                slot="append"
                type="primary"
                size="mini"
                @click.native="clickinput(11)"
                >选择图片</el-button
              >
            </el-input>
          </el-form-item>
          <el-form-item
            label="分享链接配图"
            prop="YbShareBgImg"
            v-if="aeForm.parent_id == 0"
          >
            <input
              type="file"
              size="small"
              name="file"
              @change="fileSelected(10)"
              id="file10"
              class="true-file"
              style="display: none"
            />
            <el-input
              readonly
              type="text"
              v-model="aeForm.YbShareBgImg"
              placeholder="上传分享链接配图"
              size="medium"
              style="width: 400px"
            >
              <el-button
                slot="append"
                type="primary"
                size="mini"
                @click.native="clickinput(10)"
                >选择图片</el-button
              >
            </el-input>
          </el-form-item>

          <!-- 二级分类配置列表背景图 -->
          <el-form-item
            label="列表背景图"
            v-if="aeForm.parent_id != 0 && (parentIsList || parentIsVariety)"
            prop="YbListImg"
          >
            <input
              type="file"
              size="small"
              name="file"
              @change="fileSelected(9)"
              id="file9"
              class="true-file"
              style="display: none"
            />
            <el-input
              readonly
              type="text"
              v-model="aeForm.YbListImg"
              placeholder="上传列表背景图"
              size="medium"
              style="width: 400px"
            >
              <el-button
                slot="append"
                type="primary"
                size="mini"
                @click.native="clickinput(9)"
                >选择图片</el-button
              >
            </el-input>
          </el-form-item>
          <!-- 列表、品种的二级分类 展示分享链接配图 但是不是必填的 -->
          <el-form-item
            label="分享链接配图"
            prop="YbShareBgImg_"
            v-if="aeForm.parent_id != 0 && (parentIsList || parentIsVariety)"
          >
            <input
              type="file"
              size="small"
              name="file"
              @change="fileSelected(12)"
              id="file12"
              class="true-file"
              style="display: none"
            />
            <el-input
              readonly
              type="text"
              v-model="aeForm.YbShareBgImg_"
              placeholder="上传分享链接配图"
              size="medium"
              style="width: 400px"
            >
              <el-button
                slot="append"
                type="primary"
                size="mini"
                @click.native="clickinput(12)"
                >选择图片</el-button
              >
            </el-input>
          </el-form-item>

          <el-form-item
            label="关联线上路演"
            prop="RelateVideo"
            v-if="aeForm.isLastLevel"
          >
            <el-switch
              v-model="aeForm.RelateVideo"
              inactive-color="#ededed"
            ></el-switch>
          </el-form-item>

          <el-form-item
            label="小程序端隐藏"
            prop="IsShow"
          >
            <el-switch
              v-model="aeForm.IsShow"
              inactive-color="#ededed"
            ></el-switch>
          </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>
  </div>
</template>

<script>
import mDialog from '@/components/mDialog.vue';
import { bannerupload, classifylist,classifyedit } from 'api/api.js';
export default {
  components: { mDialog },
  computed: {
    parentIsList() {
      //当前上级分类是否为列表
      let flag = false
      if (this.aeForm.show) {
        this.list.forEach(item => {
          if (item.Id == this.aeForm.parent_id) {
            if (item.ShowType == 1) {
              flag = true
            }
          }
        })
      }
      return flag
    },
    parentIsVariety() {
      //当前上级分类是否为品种
      let flag = false
      if (this.aeForm.show) {
        this.list.forEach(item => {
          if (item.Id == this.aeForm.parent_id) {
            if (item.ShowType == 3) {
              flag = true
            }
          }
        })
      }
      return flag
    },
    selectMenuOpt() {
      let arr = []
      if (this.aeForm.show) {
        this.list.forEach(item => {
          if (item.Id == this.aeForm.parent_id) {
            arr = item.ClassifyMenuList || []
          }
        })
      }
      return arr
    },

  },
  data() {
    return {
      searchVal:'',
      list: [],
      inputVisible: false,
      inputValue: '',
      ClassifyMenuList: [],
      YbFiccPcIconList: [
        {
          label: '蓝色',
          val: 'https://hzstatic.hzinsights.com/static/yb_wx/ficc_classify_bg_blue.png'
        },
        {
          label: '绿色',
          val: 'https://hzstatic.hzinsights.com/static/yb_wx/ficc_classify_bg_green.png'
        },
        {
          label: '红色',
          val: 'https://hzstatic.hzinsights.com/static/yb_wx/ficc_classify_bg_orange.png'
        },
      ],
      aeForm: {
        show: false,
        classify_name: '',
        parent_id: 0,
        abstract: '',
        descript: '',
        author: '',
        authorDsec: '',
        classifyDsec: '',
        authorTag: '',
        classifyImg: '',
        reportImg: '',
        columImg: '',
        bannerImg: '',
        avatar: '',
        label: "",
        hasTel: 0,//是否有电话会：0-否 1-是
        showType: 1,//展示形式 1-列表 2-专栏 3-品种
        Sort: '',
        YbFiccSort: '',
        YbFiccIcon: '',
        YbIconUrl: '',
        YbBgUrl: '',
        YbFiccPcIcon: '',
        IsShow: false,//是否在小程序端展示：0-隐藏 1-显示
        YbListImg: '',//小程序研报列表封面图
        YbShareBgImg: '',
        ClassifyMenuId: '',
        YbRightBanner: '',//报告合集配图
        relate: [],
        RelateVideo:false,//关联线上路演
        reportDetailShowType: 1,//详情展示形式
      },
      aerules: {
        abstract: [{
          required: true,
          message: '请输入分类简介',
          trigger: 'blur'
        }],
        descript: [{
          required: true,
          message: '请输入分类描述',
          trigger: 'blur'
        }],
        author: [{
          required: true,
          message: '请输入栏目作者',
          trigger: 'blur'
        }],
        authorDsec: [{
          required: true,
          message: '请输入作者简介',
          trigger: 'blur'
        }],
        classifyDsec: [{
          required: true,
          message: '请输入栏目简介',
          trigger: 'blur'
        }],
        classifyImg: [{
          required: true,
          message: '请上传首页配图',
          trigger: 'blur'
        }],
        reportImg: [{
          required: true,
          message: '请上传研报配图',
          trigger: 'blur'
        }],
        bannerImg: [{
          required: true,
          message: '请上传头部banner',
          trigger: 'blur'
        }],
        avatar: [{
          required: true,
          message: '请上传作者头像',
          trigger: 'blur'
        }],
        columImg: [{
          required: true,
          message: '请上传专栏配图',
          trigger: 'blur'
        }],
        label: [{
          required: true,
          message: '请输入分类标签',
          trigger: 'blur'
        }],
        hasTel: [{
          required: true,
          message: '请选择',
          trigger: 'change'
        }],
        showType: [{
          required: true,
          message: '请选择展示形式',
          trigger: 'change'
        }],
        Sort: [{
          required: true,
          message: '请输入数字',
          trigger: 'blur'
        }],
        YbFiccSort: [{
          required: true,
          message: '请输入数字',
          trigger: 'blur'
        }],
        YbFiccIcon: [{
          required: true,
          message: '上传FICC页icon',
          trigger: 'change'
        }],
        YbRightBanner: [{
          required: true,
          message: '上传报告合集配图',
          trigger: 'change'
        }],
        YbFiccPcIcon: [{
          required: true,
          message: '选择背景颜色',
          trigger: 'change'
        }],
        IsShow: [{
          required: true,
          message: '小程序端隐藏',
          trigger: 'change'
        }],
        YbListImg: [{
          required: true,
          message: '上传列表背景图',
          trigger: 'change'
        }],
        YbShareBgImg: [{
          required: true,
          message: '上传列表背景图',
          trigger: 'change'
        }],
      },
    }
  },
  created() {
    this.getlist()
  },
  methods: {
    chapterSetting(row){
      let reportType='';
			if(row.ClassifyName=='周报'){
				reportType='week'
			}else if(row.ClassifyName=='晨报'){
				reportType='day'
			}
			this.$router.push({path:'chapterVariety',query:{id:row.Id,reportType}})
    },
    showInput(index){
			if(index!=-1){
				this.ClassifyMenuList[index].inputVisible=true
				this.$nextTick(_ => {
					this.$refs.itemINput[0].$refs.input.focus();
				})
				return
			}
			this.inputVisible = true;
			this.$nextTick(_ => {
				this.$refs.saveTagInput.$refs.input.focus();
			});
		},
		handleInputConfirm() {
			let inputValue = this.inputValue;
			if (inputValue) {
				this.ClassifyMenuList.push({MenuId:0,MenuName:inputValue,inputVisible:false});
			}
			this.inputVisible = false;
			this.inputValue = '';
		},
		handleClose(index){
			this.ClassifyMenuList.splice(index,1)
		},
    //保存
    setClassifyHandle(){
      this.$refs.aeForm.validate((valid)=>{
        if(valid){
          console.log(this.aeForm);
          let params={
            ClassifyId:this.aeForm.classify_id,
            ClassifyLabel:this.aeForm.label,
            ShowType:this.aeForm.showType,
            IsShow:this.aeForm.IsShow?0:1,
            YbFiccSort:this.aeForm.YbFiccSort?Number(this.aeForm.YbFiccSort):0,
            YbFiccIcon:this.aeForm.YbFiccIcon,
            YbFiccPcIcon:this.aeForm.YbFiccPcIcon,
            YbIconUrl:this.aeForm.YbIconUrl,
            YbBgUrl:this.aeForm.YbBgUrl,
            YbListImg:this.aeForm.YbListImg,
            YbShareBgImg:this.aeForm.parent_id!=0&&(this.parentIsList||this.parentIsVariety)?this.aeForm.YbShareBgImg_:this.aeForm.YbShareBgImg,
            ClassifyMenuId:this.aeForm.ClassifyMenuId||0,
            YbRightBanner:this.aeForm.YbRightBanner||'',
            MenuList:[],
            RelateTel:this.aeForm.relate.includes(1)?1:0,
            RelateVideo:this.aeForm.RelateVideo?1:0,
            ReportDetailShowType: this.aeForm.reportDetailShowType
          }
          params.MenuList=this.ClassifyMenuList.map(item=>{
						return {
							MenuId:item.MenuId,
							MenuName:item.MenuName
						}
					})
          classifyedit(params).then(res =>{
							if( res.Ret==200 ){
								this.$message.success( res.Msg );
								this.getlist();
								this.aeForm.show=false;
							}
					});

        }
      })
    },
    cancelClassify(){
      this.aeForm.show=false
    },
    handleShowEdit(item) {
      this.aeForm = {
        show: true,
        classify_id: parseInt(item.Id),
        classify_name: item.ClassifyName,
        parent_id: item.ParentId,
        descript: item.Descript,
        author: item.ReportAuthor,
        authorDsec: item.AuthorDescript,
        classifyDsec: item.Abstract,
        authorTag: item.VipTitle,
        classifyImg: item.ReportImgUrl,
        reportImg: item.HomeImgUrl,
        columImg: item.ColumnImgUrl,
        bannerImg: item.HeadImgUrl,
        avatar: item.AvatarImgUrl,
        label: item.ClassifyLabel,
        hasTel: item.HasTeleconference,
        showType: item.ShowType,
        Sort: item.Sort,
        YbFiccSort: item.YbFiccSort,
        YbFiccIcon: item.YbFiccIcon,
        YbIconUrl: item.YbIconUrl,
        YbBgUrl: item.YbBgUrl,
        YbFiccPcIcon: item.YbFiccPcIcon,
        IsShow: item.IsShow == 0 ? true : false,//是否在小程序端展示：0-隐藏 1-显示
        YbListImg: item.YbListImg,
        YbShareBgImg: item.YbShareBgImg,
        ClassifyMenuId: item.ClassifyMenuId || '',
        YbRightBanner: item.YbRightBanner || '',
        relate: [item.RelateTel == 1 ? 1 : null, item.RelateVideo == 1 ? 2 : null],
        RelateVideo:item.RelateVideo == 1?true:false,
        isLastLevel: item.Child ? false : true,
        reportDetailShowType: item.ReportDetailShowType||1
      }
      this.ClassifyMenuList = item.ClassifyMenuList ? item.ClassifyMenuList.map(item => {
        return {
          MenuId: item.MenuId,
          MenuName: item.MenuName,
          inputVisible: false
        }
      }) : []
      //若编辑的为列表、品种下的二级分类 需要计算YbShareBgImg_
      //已填写则获取已填写内容
      if (item.YbShareBgImg) {
        this.aeForm.YbShareBgImg_ = item.YbShareBgImg
      } else {//若未填写则取一级分类的YbShareBgImg
        this.aeForm.YbShareBgImg_ = this.getParentYbShareBgImg(item.ParentId)
      }
      this.$nextTick(() => {
        this.$refs.aeForm.clearValidate();
      })
    },
    //根据上级分类id获取YbShareBgImg
    getParentYbShareBgImg(id) {
      let YbShareBgImg = ''
      let parent = this.list.find((item) => { return item.Id === id })
      if (!parent) return
      YbShareBgImg = parent.YbShareBgImg || ''
      return YbShareBgImg
    },
    getlist() {  //获取列表
      let params = { KeyWord: this.searchVal };
      this.listLoading = true;
      classifylist(params).then((res) => {
        if (res.Ret == 200) {
          this.list = res.Data.List || [];

        }
        this.listLoading = false;
      });
    },
    clickinput(type) {  //上传模拟点击
      $(`#file${type}`).click();
    },
    fileSelected(type) {  //选择文件上传
      const that = this;
      if (document.getElementById('file' + type).files[0]) {
        let hostfile = document.getElementById('file' + type).files[0];
        let size = Math.floor(hostfile.size / 1024 / 1024);
        if (size > 200) {
          that.$message.error('上传文件大小不能大于200M！');
          hostfile = {};
          return false
        }
        if (hostfile.name.toLowerCase().includes('.png') || hostfile.name.toLowerCase().includes('.jpg') || hostfile.name.toLowerCase().includes('.jpeg')) {
          let form = new FormData();
          form.append('file', hostfile);  //hostfile.name
          that.uploadloading = true;
          bannerupload(form).then((res) => {
            if (res.Ret === 200) {
              if (type == 1) {
                that.aeForm.classifyImg = res.Data.ResourceUrl;
              } else if (type == 2) {
                that.aeForm.bannerImg = res.Data.ResourceUrl;
              } else if (type == 3) {
                that.aeForm.avatar = res.Data.ResourceUrl
              } else if (type == 4) {
                that.aeForm.columImg = res.Data.ResourceUrl
              } else if (type == 5) {
                that.aeForm.reportImg = res.Data.ResourceUrl
              } else if (type == 6) {
                that.aeForm.YbFiccIcon = res.Data.ResourceUrl
              } else if (type == 7) {
                that.aeForm.YbIconUrl = res.Data.ResourceUrl
              } else if (type == 8) {
                that.aeForm.YbBgUrl = res.Data.ResourceUrl
              } else if (type == 9) {
                this.aeForm.YbListImg = res.Data.ResourceUrl
              } else if (type == 10) {
                this.aeForm.YbShareBgImg = res.Data.ResourceUrl
              } else if (type == 11) {
                this.aeForm.YbRightBanner = res.Data.ResourceUrl
              } else if (type == 12) {
                this.aeForm.YbShareBgImg_ = res.Data.ResourceUrl
              }
            }
            $("#file" + type).val('');
            hostfile = {};
          });
        } else {
          that.$message.error('上传文件格式不正确！');
        }
      }
    },
  },
}
</script>

<style lang="scss">
.el-cascader .el-input {
  width: 100%;
}
.report-variety-page {
  .content-box {
    .el-tree-node__content {
      padding-top: 10px;
      padding-bottom: 10px;
      border-bottom: 1px solid #c8cdd9;
    }
  }
}
</style>
<style lang="scss" scoped>
.top-wrap {
  display: flex;
  justify-content: flex-end;
  background: #ffffff;
  border-radius: 4px;
  padding: 10px 20px;
}
.content-box {
  padding: 20px;
  margin-top: 20px;
  height: calc(100vh - 230px);
  overflow-y: auto;
  background-color: #ffffff;
  .classify-item-wrap {
    flex: 1;
    padding-right: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .tag {
      display: inline-block;
      min-width: 76px;
      line-height: 30px;
      text-align: center;
      &.open {
        background-color: #ecf2fe;
        color: #0052d9;
      }
      &.close {
        background-color: #0052d9;
        color: #fff;
      }
    }
    .opt-box {
      .icon-drag,
      .icon-set {
        width: 16px;
        height: 16px;
        margin-left: 10px;
      }
    }
  }
}
</style>