<!--
 * @Author: your name
 * @Date: 2020-12-02 10:27:53
 * @LastEditTime: 2020-12-11 17:15:00
 * @LastEditors: Please set LastEditors
 * @Description: 类别管理
 * @FilePath: \rs-cloud-platform-ui\src\views\webSiteManagement\industryApplication\applicationList\index.vue
-->
<template>
  <div id="ApplicationCate">
    <!-- 操作表格栏 -->
    <div class="operators">
      <div class="status">
        <span>所有状态</span>
        <el-select v-model="currentStatus" placeholder="全部">
          <el-option
            v-for="item in status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="types">
        <span>应用类别</span>
        <el-col :span="16">
          <el-input
            v-model="currentTypeName"
            placeholder="请输入类别"
            size="100px"
          ></el-input>
        </el-col>
      </div>
      <div class="sorts">
        <span>排序</span>
        <el-select v-model="currentSort" placeholder="全部">
          <el-option
            v-for="item in sorts"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="controls">
        <div
          class="item"
          v-for="(item, index) in operatorControls"
          :key="index"
          @click.stop="clickOperator(index)"
        >
          {{ item.name }}
        </div>
      </div>
      <div class="addCate">
          <div class="add" @click.stop="addCate">
              添加类别
          </div>
      </div>
    </div>
    <!-- 添加类别弹框 -->
    <el-dialog :title="typeManagerTitle" :visible.sync="typeManagerVisible" append-to-body>
        <div id="addCateManager">
          <el-form ref="form" :rules="rules" :model="form" label-width="80px">
            <el-form-item label="应用类别" prop="type">
                <el-col :span="12">
                    <el-input v-model="form.type" placeholder="请输入资讯标题"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="封面图" prop="coverImg">
                <singleImageX :value="form.coverImg" @input="onPreview"></singleImageX>
            </el-form-item>
            <el-form-item label="简介" prop="introduce">
                <el-col :span="12">
                    <el-input v-model="form.introduce" placeholder="请输入资讯简介"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-col :span="12">
                    <el-input type="number" v-model="form.sort" placeholder="请输入序号"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="分类设置" prop="level">
              <el-radio-group v-model="form.level">
                <el-radio label="一级类目"></el-radio>
                <el-radio label="二级类目"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="父级" prop="father" v-show="form.showFather">
              <el-select v-model="currentType" placeholder="全部">
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="closeTypeManager">取消</el-button>
                <el-button type="primary" @click="onSubmit">确定</el-button>
            </el-form-item>
          </el-form>
        </div>
    </el-dialog>
    <!-- 表格 -->
    <div class="table">
      <el-table :data="tableData" border fit highlight-current-row style="width: 100%">
        <el-table-column label="序号" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.index }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应用类别" width="200" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="封面图" width="80" align="center">
          <template slot-scope="scope">
            <span>
              <img
                class="icon"
                :src="scope.row.icon.url"
                @click="showPreview(scope.row.icon)"
              />
            </span>
          </template>
        </el-table-column>
        <el-table-column label="简介" align="center">
          <template slot-scope="scope">
            <span class="introduce">{{ scope.row.introduce }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类目级别" align="center">
          <template slot-scope="scope">
            <span class="typelevel">{{ scope.row.pid != 0 ? "二级" : "一级"}}</span>
          </template>
        </el-table-column>
        <el-table-column label="父级" align="center">
          <template slot-scope="scope">
            <span class="typelevel">{{ getFatherTypeName(scope.row.pid) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.status==1?"上架":"下架" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <!-- <span>{{scope.row.operator}}</span> -->
            <span>
              <div class="operators">
                <div class="edit" @click.stop="changeCate(scope.row)">编辑</div>
                <div class="offshelf" v-if="scope.row.status==1" @click.stop="changeTypeStatus(scope.row)">下架</div>
                <div class="upshelf" v-else @click.stop="changeTypeStatus(scope.row)">上架</div>
                <div class="delete" @click.stop="delType(scope.row)">删除</div>
              </div>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="typePagination">
        <el-pagination
        @size-change="changeHandleSize"
        @current-change="changeHandleCurrent"
        :current-page.sync="typePagination.currentPage"
        :page-sizes="[10,20,30,40]"
        :page-size="typePagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="typePagination.total">
        </el-pagination>
    </div>
    <!-- 使用图片查看器预览当前缩略图 -->
    <el-image-viewer
      v-show="currentIcon.showPreview"
      :on-close="closePreview"
      :url-list="[currentIcon.url]"
    />
  </div>
</template>

<script>
// 导入组件
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import singleImageX from '@/components/Upload/singleImageX';
// 导入请求
import {
  getAllApplicationType,
  getListApplicationType,
  addUpdateApplicationType,
} from "api/website/industryApplication/index";
export default {
  name: "ApplicationList",
  components: {
    ElImageViewer,
    singleImageX
  },
  data() {
    return {
      currentIcon: "",
      
      // 功能按钮
      operatorControls: [
        {
          name: "搜索",
        },
        {
          name: "清空搜索",
        },
      ],
      //所有状态
      status: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "1",
          label: "上架",
        },
        {
          value: "2",
          label: "下架",
        },
      ],
      currentStatus: "",
      // 类别
      currentTypeName: "",
      typesState: [],
      types: [],
      currentType: "",
      // 排序
      sorts: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "1",
          label: "降序",
        },
        {
          value: "2",
          label: "升序",
        },
      ],
      currentSort: '',
      // 表格数据
      tableDataCache: [],
      tableData: [
        // {
        //   id: "1",
        //   type: "类别",
        //   icon: {
        //     url: "https://onemap.obtdata.com/wx/download/world.png",
        //     showPreview: false,
        //   },
        //   introduce: "简介",
        //   sort: "排序",
        //   status: "状态",
        // },
      ],
      typePagination: {
          currentPage: 1,// 当前页码
          pageSize: 10,// 每页查询数量
          total: 0,// 总记录数量
      },
      typeManagerTitle: "添加类别",
      typeManagerVisible: false,
      rules: {
        type: [{ required: true, message: '文案有误', trigger: 'blur' }],
        introduce: [{ required: true, message: '请输入简介', trigger: 'blur' }],
        coverImg: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
        level: [{ required: true, message: '请选择级别', trigger: 'blur' }],
        father: [{ required: true, message: '请选择父级类别', trigger: 'blur' }],
      },
      form:{
        type: '',
        coverImg: '',
        introduce: '',
        sort: '',
        level: '一级类目',
        showFather: false
      },
      editType: '',
    };
  },
  watch:{
    "form.level":{
      deep: true,
      handler(newVal){
        console.log(newVal)
        if(newVal=="二级类目"){
          this.pullAllApplicationType()
          this.form.showFather = true
        }else{
          this.form.showFather = false
        }
      }
    }
  },
  mounted() {
    // 获取所有类型用于下拉框
    this.pullAllApplicationType()
    // 分页获取类型用于表格
    this.pullListApplicationType()
  },
  methods: {
    closeTypeManager(){
      this.typeManagerVisible = false
      this.$bus.$emit('upload-clearFiles')
    },
    getFatherTypeName(pid){
      console.log("typesState",this.typesState)
      let father = this.typesState.find(ele => ele.id == pid)
      return father ? father.title : ""
    },
    clickOperator(index){
      console.log("index=>",index)
      if(index==1){ 
        this.currentStatus = ''
        this.currentTypeName = ''
        this.currentSort = ''
      }
      this.pullListApplicationType()
    },
    // 添加类别
    addCate(){
      this.typeManagerVisible = true
      this.typeManagerTitle = "添加类别"
      this.form.type = ''
      this.form.coverImg = ''
      this.form.introduce = ''
      this.form.sort = ''
    },
    // 修改类别
    changeCate(type){
      this.typeManagerVisible = true
      this.typeManagerTitle = "修改类别"
      this.editType = type
      this.form.type = type.type
      this.form.coverImg = type.icon.url
      this.form.introduce = type.introduce
      this.form.sort = type.sort
    },
    // 获取所有应用类型
    pullAllApplicationType(){
      this.typesState = []
      this.types = []
      getAllApplicationType().then(res => {
        if(res.status == 200){
          // console.log("获取所有的应用类型=>",res)
          res.data.forEach(element => {
            this.typesState.push(element)
            if(element.isDel==0&&element.pid==0){
              this.types.push({
                value: element.id,
                label: element.title
              });
            }
          });
          if(this.types.length>0){
            this.currentType = this.types[0].value
          }
        }
      })
    },
    // 分页获取应用类型
    pullListApplicationType(){
      getListApplicationType({
        page: this.typePagination.currentPage,
        limit: this.typePagination.pageSize,
      }).then(res => {
        if(res.status==200){
          this.tableDataCache = []
          this.tableData = []
          // console.log("分页数据=>",res)
          this.typePagination.total = res.data.totalCount
          res.data.data.forEach(element => {
            this.tableDataCache.push(element)
          })
          console.log("获取到的分页类别信息=>",this.tableDataCache)
          this.screenTableData()
          // this.tableDataCache.forEach(element => {
          //   this.tableData.push({
          //     id: element.id,
          //     type: element.title,
          //     icon: {
          //       url: element.detailImg,
          //       showPreview: false,
          //     },
          //     coverImg: element.detailImg,
          //     crtTime: element.crtTime,
          //     introduce: element.detail,
          //     sort: element.rank,
          //     status: element.status,
          //     isDel: element.isDel,
          //     pid: element.pid,
          //     updTime: element.updTime,
          //     indexShow: element.indexShow
          //   })
          // })
        }
      })
    },
    // 为表格数据添加过滤条件
    screenTableData(){
      console.log("分页数据的缓存=>",this.tableDataCache)
      this.tableData = []
      let index = 0
      this.tableDataCache.forEach(element => {
        if(element.isDel==0){
          this.tableData.push({
            index: ((this.typePagination.currentPage-1)*this.typePagination.pageSize)+(++index),
            id: element.id,
            type: element.title,
            icon: {
              url: element.detailImg,
              showPreview: false,
            },
            coverImg: element.detailImg,
            crtTime: element.crtTime,
            introduce: element.detail,
            sort: element.rank,
            status: element.status,
            isDel: element.isDel,
            pid: element.pid,
            updTime: element.updTime,
            indexShow: element.indexShow
          })
        }
      })
      if(this.currentStatus!=''){
        this.tableData = this.tableData.filter(element => element.status == this.currentStatus)
      }
      if(this.currentTypeName!=''){
        // this.tableData = this.tableData.filter(element => element.type == this.currentTypeName)
        this.tableData = this.tableData.filter(element => {
          //正则表达式
          let reg = new RegExp(this.currentTypeName);
          return element.type.match(reg)
        })
      }
      if(this.currentSort!=''){
        // 1是降序,2是升序
        if(this.currentSort==1){
          this.tableData.sort((obj1,obj2)=>{
              let val1 = parseInt((obj1.id+""))
              let val2 = parseInt((obj2.id+""))
              if(val1<val2){
                  return 1
              }else if(val1>val2){
                  return -1
              }else{
                  return 0
              }
          })
        }else{
          // 升序
          this.tableData.sort((obj1,obj2)=>{
              let val1 = parseInt((obj1.id+""))
              let val2 = parseInt((obj2.id+""))
              if(val1<val2){
                  return -1
              }else if(val1>val2){
                  return 1
              }else{
                  return 0
              }
          })
        }
      }
    },
    // 删除类型
    delType(type){
      this.$confirm('确定继续执行该操作吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(() => {
        type.isDel = 1
        addUpdateApplicationType({
          id: type.id+'',
          title: type.type,
          detail: type.introduce,
          coverImg: type.coverImg,
          detailImg: type.icon.url,
          status: type.status,
          rank: type.sort,
          indexShow: type.indexShow,
          pid: type.pid,
          isDel: type.isDel+''
        }).then(res => {
          if(res.status==200){
            this.$message({
                message: "删除成功!!!",
                type: 'success'
            });
            this.pullListApplicationType()
            // let index = this.tableData.findIndex(ele => ele.id == type.id)
            // if(index!=-1){
            //   this.tableData.splice(index,1)
            // }
          }else{
            this.$message.error('操作失败,请稍后重试!!!');
          }
        })
      })
    },
    // 改变类型状态 
    changeTypeStatus(type){
      console.log("status",type.status)
      let message = ""
      if(type.status==1){//当前状态为上架
        type.status = 2
        message = "下架成功!!!"
      }else{
        type.status = 1
        message = "上架成功!!!"
      }
      addUpdateApplicationType({
        id: type.id+'',
        title: type.type,
        detail: type.introduce,
        coverImg: type.coverImg,
        detailImg: type.icon.url,
        status: type.status,
        rank: type.sort,
        indexShow: type.indexShow,
        pid: type.pid,
        isDel: type.isDel+''
      }).then(res => {
        if(res.status==200){
          this.$message({
              message: message,
              type: 'success'
          });
          this.pullListApplicationType()
        }else{
          this.$message.error('操作失败,请稍后重试!!!');
        }
      })
    },
    changeHandleSize(val) {
        // console.log(`每页 ${val} 条`);
        this.typePagination.pageSize = val
        this.pullListApplicationType()
    },
    changeHandleCurrent(val) {
        // console.log(`当前页: ${val}`);
        this.typePagination.currentPage = val
        this.pullListApplicationType()
    },
    onPreview(url){   
        this.form.coverImg = url
    },
    showPreview(icon) {
      this.currentIcon = icon;
      this.currentIcon.showPreview = true;
    },
    closePreview() {
      this.currentIcon.showPreview = false;
    },
    onSubmit() {
      let message = this.typeManagerTitle == "添加类别" ? "添加" : "修改"
      if(this.form.type==''){
        this.$message.error(message+'失败,名称为空!!!');
      }else if(this.form.coverImg==''){
        this.$message.error(message+'失败,封面未上传!!!');
      }else if(this.form.introduce==''){
        this.$message.error(message+'失败,简介为空!!!');
      }else if(this.form.sort<0){
        this.$message.error(message+'失败,排序值有误!!!');
      }else{
        let data 
        if(message=="添加"){
          data = {
            title: this.form.type,
            detail: this.form.introduce,
            coverImg: this.form.coverImg,
            detailImg: this.form.coverImg,
            status: 1,
            rank: this.form.sort,
            indexShow: 1,
            pid: this.form.showFather ? this.currentType : 0,
          }
        }else{// 修改
          data = {
            id: this.editType.id+'',
            title: this.form.type ,
            detail: this.form.introduce,
            coverImg: this.form.coverImg,
            detailImg: this.editType.icon.url,
            status: this.editType.status,
            rank: this.form.sort,
            indexShow: this.editType.indexShow,
            pid: this.editType.pid,
            isDel: this.editType.isDel+''
          }
        }
        addUpdateApplicationType(data).then(res => {
          if(res.status==200){
            this.$message({
                message: message+"成功!!!",
                type: 'success'
            });
            this.typeManagerVisible = false
            this.pullListApplicationType()
            this.$bus.$emit('upload-clearFiles')
          }else{
            this.$message.error('操作失败,请稍后重试!!!');
          }
        })
      }
    }
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
#ApplicationCate {
  margin: 0 1% 0 1%;
  width: 98%;
  height: auto;
  #addCateManager{
    padding: 0 5%;
    width: 90%;
    height: auto;
  }
  .operators {
    // margin: 0 1% 0 1%;
    width: 100%;
    height: 68px;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    .sorts,.status,.types {
      width: auto;
      height: 46px;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      span {
        margin: 0 10px 0 20px;
      }
    }
    .addCate{
      width: 240px;
      height: 46px;
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      align-items: center;
      overflow: hidden;
      .add{
        width: 50%;
        height: 36px;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
        background-color: #5178F2;
        color: #FFFFFF;
        cursor: pointer;
      }
    }
    .controls {
      margin-left: 40px;
      width: 260px;
      height: 46px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      .item {
        width: 120px;
        height: 36px;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        font-weight: 400;
        color: #5178f2;
        border: 1px solid #5178f2;
        border-radius: 5px;
        cursor: pointer;
      }
    }
  }
  .table {
    margin: 1% 1% 0 1%;
    width: 98%;
    height: auto;
    span {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      .icon {
        width: 50px;
        height: 50px;
        object-fit: cover;
        cursor: pointer;
      }
      .operators {
        width: 300px;
        height: 46px;
        display: flex;
        flex-direction: row;
        justify-content: space-around;
        align-items: center;
        .edit,
        .upshelf,
        .offshelf,
        .delete {
          width: auto;
          height: 36px;
          display: flex;
          flex-direction: row;
          justify-content: center;
          align-items: center;
          cursor: pointer;
        }
        .edit,.upshelf{
          color: #1890ff;
        }
        .offshelf {
          color: #A6A9AD;
        }
        .delete {
          color: #fe4066;
        }
      }
    }
  }
  .typePagination{
    margin: 1% 1% 0 1%;
    width: 98%;
    height: auto;
  }
}
</style>