<template>
  <div id="chapter-settring-container">
    <div class="head-buttons-zone">
      <el-button @click="addChapter" type="primary" style="width: 112px;">添加章节</el-button>
    </div>
    <div class="tablle-zone">
      <el-table :data="tableData" style="border:1px solid #eaeaea;" header-row-class-name="chapter-table-header">
        <el-table-column label="章节名称" prop="ReportChapterTypeName" class-name="chapter-name">
          <template slot-scope="{row}">
            {{row.ReportChapterTypeName}}
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="operation" width='300' align="center">
          <template slot-scope="{row}">
            <span class="editsty" style="margin-right:12px;" @click="setPermission(row)">权限配置</span>
            <span class="editsty" style="margin-right:12px;" @click="editChapter(row)">编辑</span>
            <span class="deletesty" style="color: #D1433A;" @click="deleteChapter(row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加/编辑 章节 -->
    <el-dialog :title="dialogTitle" :modal-append-to-body='false' :visible.sync="addDialogShow" 
    :close-on-click-modal="false" :center="true" v-dialogDrag width="620px" @close="addDialogClose">
      <div style="display: flex;align-items: center;justify-content: center;">
        <el-form :model="addForm" label-width="95px" :rules="addFormRules" ref="addForm">
          <el-form-item label="章节名称" prop="ReportChapterTypeName">
            <el-input v-model="addForm.ReportChapterTypeName" style="width: 317px;" placeholder="请输入章节名称"></el-input>
          </el-form-item>
          <el-form-item label="未选中icon" prop="UnselectedImage">
            <input type="file" size="small" name="file" @change="fileSelected(1)" id="file1" class="true-file" style="display: none;">
            <el-input type="text" v-model="addForm.UnselectedImage" placeholder="上传图片" size="medium">
              <el-button slot="append" type="primary" size="mini" @click.native="clickinput(1)">选择图片</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="选中icon" prop="SelectedImage">
            <input type="file" size="small" name="file" @change="fileSelected(2)" id="file2" class="true-file" style="display: none;">
            <el-input type="text" v-model="addForm.SelectedImage" placeholder="上传图片" size="medium">
              <el-button slot="append" type="primary" size="mini" @click.native="clickinput(2)">选择图片</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="带字icon" prop="WordsImage">
            <input type="file" size="small" name="file" @change="fileSelected(3)" id="file3" class="true-file" style="display: none;">
            <el-input type="text" v-model="addForm.WordsImage" placeholder="上传图片" size="medium">
              <el-button slot="append" type="primary" size="mini" @click.native="clickinput(3)">选择图片</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="章节配图" prop="EditImgUrl">
            <input type="file" size="small" name="file" @change="fileSelected(4)" id="file4" class="true-file" style="display: none;">
            <el-input type="text" v-model="addForm.EditImgUrl" placeholder="上传图片" size="medium">
              <el-button slot="append" type="primary" size="mini" @click.native="clickinput(4)">选择图片</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="列表排序" prop="Sort">
            <el-input-number v-model="addForm.Sort" placeholder="请输入数字" ></el-input-number>
          </el-form-item>
          <el-form-item label="小程序隐藏" prop="mpHidden">
            <el-switch v-model="addForm.mpHidden" inactive-color="#ededed"></el-switch>
          </el-form-item>
        </el-form>
      </div>
      <div solt="footer" style="padding: 20px 0;text-align: center;">
        <el-button size="medium" style="width:130px;" @click="addDialogShow=false">取消</el-button>
        <el-button type="primary" size="medium" style="margin-left: 16px;width:130px ;" @click="addChapterSave">保存</el-button>
      </div>
    </el-dialog>
    <!-- 权限配置弹窗 -->
		<PermissionDialog :isShow.sync="permissionDiashow" permissionType="chapterType"
    :id="chapterId" @saveConfig="savePermission" :haveReset="false" />
  </div>
</template>

<script lang="js">
import { bannerupload ,getchapterTypeList,addChapterType,editChapterType,
  deleteChapterType,setchapterTPermission} from 'api/api.js';
import PermissionDialog from './components/PermissionDialog.vue'

  export default {
    name:"chapterSetting",
    components:{PermissionDialog},
    data() {
      return {
        tableData:[],
        dialogTitle:"", // 弹窗标题
        // 添加/编辑弹窗
        addDialogShow:false,
        addForm:{
          ReportChapterTypeName:"",
          ResearchType:"",
          UnselectedImage:"",
          SelectedImage:"",
          WordsImage:"",
          EditImgUrl:"",
          Sort:0,
          mpHidden:false
        },
        // 列表最后一个的排序值
        lastSort:0,
        researchType:'',// day-晨报；week-周报
        addFormRules:{
          ReportChapterTypeName:{required:true,message:'章节名称不能为空',trigger:'blur'},
          UnselectedImage:{required:true,message:'未选中icon不能为空',trigger:['blur','change']},
          SelectedImage:{required:true,message:'选中icon不能为空',trigger:['blur','change']},
          WordsImage:{required:true,message:'带字icon不能为空',trigger:['blur','change']},
          EditImgUrl:{required:true,message:'章节配图不能为空',trigger:['blur','change']},
          Sort:{required:true,message:'列表排序不能为空',trigger:['blur','change']},
          mpHidden:{required:true,message:'请选择小程序是否隐藏',trigger:'change'}
        },
        // 权限配置弹窗
        permissionDiashow:false,
        chapterId:1
      }
    },
    created() {
      // 类型 周报-晨报
      this.addForm.ResearchType=this.researchType=this.$route.query.reportType=='week'?'week':'day'
      this.getList()
    },
    methods: {
      // 获取章节类型列表
      getList(){
        getchapterTypeList({ReportType:this.researchType,PageSize:10000,CurrentIndex:1}).then(res=>{
          if(res.Ret == 200){
            this.tableData=res.Data.List || []
            this.lastSort=this.addForm.Sort=this.tableData[this.tableData.length-1].Sort+1
          }
        })
      },
      addChapter(){
        this.dialogTitle="添加章节"
        this.addDialogShow=true
        console.log(this.addForm);
      },
      editChapter(row){
        // console.log(row);
        this.addForm={
          ...this.addForm,
          ReportChapterTypeName:row.ReportChapterTypeName,
          ReportChapterTypeId:row.ReportChapterTypeId,
          Sort:row.Sort,
          UnselectedImage:row.UnselectedImage,
          SelectedImage:row.SelectedImage,
          EditImgUrl:row.EditImgUrl,
          WordsImage:row.WordsImage,
          mpHidden:row.IsShow==0?true:false
        }
        // console.log(this.addForm);
        this.dialogTitle="编辑章节"
        this.addDialogShow=true
      },
      // 设置权限
      setPermission(row){
        this.chapterId=row.ReportChapterTypeId
        this.permissionDiashow=true
      },
      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
            bannerupload(form).then((res) => {
              if( res.Ret === 200 ){
                if(type == 1) {
                  that.addForm.UnselectedImage=res.Data.ResourceUrl;
                }else if(type == 2) {
                  that.addForm.SelectedImage=res.Data.ResourceUrl;
                }else if(type == 3) {
                  that.addForm.WordsImage=res.Data.ResourceUrl
                }else if(type == 4) {
                  that.addForm.EditImgUrl=res.Data.ResourceUrl
                }
              }
              $("#file"+type).val('');
              hostfile = {};
            });
          }else{
            that.$message.error('上传文件格式不正确！');
          }
		    } 
		  },
      // 保存
      addChapterSave(){
        this.$refs.addForm.validate((valid)=>{
          if(valid){
            // 添加小程序是否显示参数 0显示，1隐藏
            let params={...this.addForm,IsShow:this.addForm.mpHidden?0:1}
            // 请求方法
            let requestMethod;
            // console.log(params);
            if(params.ReportChapterTypeId){
              // 编辑
              requestMethod=editChapterType
            }else{
              // 新增
              requestMethod=addChapterType
            }
            requestMethod(params).then(res=>{
              if(res.Ret == 200){
                this.$message.success(`${this.dialogTitle}成功`)
                this.addDialogShow=false
                this.getList()
              }
            })
          }
        })
      },
      // 新增/编辑 弹窗关闭回调
      addDialogClose(){
        this.addForm={
          ReportChapterTypeName:"",
          ResearchType:this.researchType,
          UnselectedImage:"",
          SelectedImage:"",
          WordsImage:"",
          EditImgUrl:"",
          Sort:this.lastSort,
          mpHidden:false
        }
        setTimeout(()=>{
          this.$refs.addForm.clearValidate()
        },20)
      },
      // 保存
      savePermission(item){
        // console.log(item);
        setchapterTPermission({ReportChapterTypeId:item.Id,ChartPermissionIdList:item.ChartPermissionIdList}).then(res=>{
          if(res.Ret==200){
            this.$message.success('权限配置成功')
            this.permissionDiashow=false
          }
        })
      },
      // 删除章节类型
      deleteChapter(row){
        this.$confirm("确认删除这个章节吗?", "提示", {
          type: "warning"
        }).then(() => {
          deleteChapterType({ReportChapterTypeId:row.ReportChapterTypeId}).then(res=>{
            if(res.Ret==200){
              this.$message.success('删除成功')
              this.getList()
            }
          })
        })
        .catch(() => {});
      }
    },
  }
</script>

<style lang="scss" scoped>
  #chapter-settring-container{
    min-height: calc(100vh - 110px);
    box-sizing: border-box;
    .head-buttons-zone{
      background-color: white;
      padding: 20px 30px;
      border: solid 1px #DCDFE6;
      border-radius: 2px;
      box-shadow: 0px 2px 12px 0px rgba(107, 127, 199, 0.25);
      position: relative;
      z-index: 2;
    }
    .tablle-zone{
      background-color: white;
      padding: 30px;
      border: solid 1px #eee;
      box-sizing: border-box;
    }
  }
</style>
<style lang="scss">
#chapter-settring-container{
  .chapter-table-header{
    color: #333;
  }
  .chapter-name{
    padding-left: 60px;
  }
  .el-input{
    width: 100%;
  }
}

</style>