<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="标题" prop="tatle">
        <el-input
          v-model="queryParams.tatle"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:mes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:mes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:mes:remove']"
        >删除</el-button>
      </el-col>
    </el-row>


    <!--    <div class="block">-->
    <!--      <span class="demonstration">单选选择任意一级选项</span>-->
    <!--      <el-cascader-->
    <!--        :options="options"-->
    <!--        :props="{ checkStrictly: true }"-->
    <!--        clearable>-->

    <!--      </el-cascader>-->
    <!--    </div>-->



    <el-table v-loading="loading" :data="mesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="信息标题" align="center" prop="tatle" />
      <el-table-column label="栏目名称" align="center" prop="documentType" />

      <el-table-column label="发布时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="发布人" align="center" prop="createBy" />
      <!--      <el-table-column label="修改人" align="center" prop="updateBy" />-->
      <el-table-column label="显示状态" align="center" prop="xsState"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.xsState!='审核通过'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleqs(scope.row)"
            v-hasPermi="['system:mes:edit']"
          >审核</el-button>
          <el-button
            v-if="scope.row.xsState!='待审核'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:mes:edit']"
          >详情</el-button>
          <el-button
            v-if="scope.row.xsState!='审核通过'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:mes:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:mes:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" :show-close="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="显示"prop="xsState">
          <el-select v-model="form.xsState" >
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="typeId">
          <el-input v-model="form.typeId" placeholder="请输入优先级,数值越大级别越高" />
        </el-form-item>
        <el-form-item label="信息标题" prop="tatle">
        <el-input v-model="form.tatle" placeholder="请输入标题" />
      </el-form-item>
        <el-form-item label="文档类别" prop="documentType">
          <el-cascader
            v-model="doc"
            :options="options"
            @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="缩略图" prop="img">
          <el-upload
            list-type="picture-card"
            class="upload-file"
            :before-upload="handleBeforeImg"
            :before-remove="beforeRemoveImg"
            :on-preview="handlePreviewImg"
            :on-remove="handleRemoveImg"
            :show-file-list="true"
            :file-list="img.oldFileList"
            :action=actionUp
            multiple
            :http-request="fileRequestImg"
          >点击上传图片
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="附件上传" prop="putFilePath">
          <el-upload
            class="upload-file"
            :before-upload="handleBefore"
            :before-remove="beforeRemove"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :show-file-list="true"
            :file-list="mail.oldFileList"
            :action=actionUp
            multiple
            :http-request="fileRequest"
          >
            <div slot="tip" class="el-upload__tip"></div>
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-upload"
              size="mini"
            >上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件详情" prop="fileDetails"style="height: 250px;">
          <Editor v-model="form.fileDetails"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-input v-model="fujianPath" v-show="false"/>
        <el-input v-model="fujianName" v-show="false"/>
        <!--v-if="form.xsState!='1'" -->
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>

</template>

<script>
  import { listMes, getMes, delMes, addMes, updateMes, exportMes,uploadFile,uploadFileImg,check } from "@/api/information/mes";
  import { listDept } from "@/api/information/docmenu";
  import Editor from '@/components/Editor';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "Mes",
    components: {
      Editor,
      Treeselect
    },
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        //下拉选框
        doc: [],
        options: [],
        deptList:[],

        content: this.value,
        radio: '1',
        fileList: [],
        mail: {
          oldFileList: [],
          fileList: []
        },
        img: {
          oldFileList: [],
          fileList: []
        },
        actionUp:'aaaa',//接口地址
        fujianName:'',
        fujianPath:'',
        imgPath:'',
        status:'',
        mailGuid:this.$route.query.id,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 【请填写功能名称】表格数据
        mesList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          tatle: undefined,
          documentType: undefined,
          img: undefined,
          putFilePath: undefined,
          fileDetails: undefined,
          xsState: undefined,
          typeId: undefined,
          flg: undefined,
          submitTime: undefined,
          lastUpdate: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          tatle: [
            { required: true, message: "标题不能为空", trigger: "blur" }
          ],
          // tatle: [
          //   { required: true, message: "标题不能为空", trigger: "blur" }
          // ],
          // documentType: [
          //   { required: true, message: "文档类别不能为空", trigger: "blur" }
          // ],
          fileDetails: [
            { required: true, message: "文件详情不能为空", trigger: "blur" }
          ],
          xsState: [
            { required: true, message: "显示状态(0-待审核,1-审核通过)不能为空", trigger: "blur" }
          ],
          typeId: [
            { required: false, message: "类别id（0-一级目录,2-二级目录）不能为空", trigger: "blur" }
          ],
          flg: [
            { required: true, message: "0-未删除1-已删除不能为空", trigger: "blur" }
          ],
          submitTime: [
            { required: true, message: "提交时间不能为空", trigger: "blur" }
          ],
          updateTime: [
            { required: true, message: "修改时间不能为空", trigger: "blur" }
          ],
          lastUpdate: [
            { required: true, message: "最后修改人不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.getList();

    },
    methods: {
      /** 审核按钮操作 */
      handleqs(row) {
        const ids = row.id || this.ids;

        // alert(ids)
        this.$confirm('是否确认审核通知?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return check(ids);

        }).then(() => {
          this.getList();
          this.msgSuccess("审核成功");
        }).catch(function() {});
      },

      // dgdfg(){
      //   for(var i = 0; i < this.options.length ; i++){
      //
      //     if(this.options[i].children == ''){
      //       delete this.options[i].children;
      //     }
      //   }
      //
      //
      // },

      /** 图片上传---开始  */
      handleBeforeImg(file) {
      },
      handlePreviewImg(file) {
        // 预览,一些文件因为格式问题无法预览。推荐使用a标签，src为文件的下载地址，点击即可下载,参照录音
        window.open(file.url);
      },
      handleRemoveImg(file) {
        // 移除
        this.img.oldFileList.forEach((item1, index) => {
          if (item1.uid === file.uid) {
            //删除
            this.img.oldFileList.splice(index, 1)
            let imgPathArr = this.imgPath.split(',');
            //重名
            for (var i = 0; i < imgPathArr.length; i++) {
              if (process.env.VUE_APP_BASE_API +imgPathArr[i] == file.url) {
                //   ("11")
                //放一起的目的是 解决重名引起的 账号和名称不对应 问题
                imgPathArr.splice(i, 1);
                break;
              }
            }
            this.imgPath = imgPathArr.join(',');
          }
        });
      },
      beforeRemoveImg(file, fileList) {
        return this.$confirm(`确定移除？`);
      },
      fileRequestImg(item1) {
        let uploadData = new FormData()
        uploadData.append('file',item1.file)
        uploadFileImg(uploadData).then(response => {
          if (response.code === 200) {
            this.imgPath += response.url + ',';
            if (this.img.oldFileList!=null){
              this.img.oldFileList.push({
                url: process.env.VUE_APP_BASE_API + response.url
              });
              console.log(process.env.VUE_APP_BASE_API + response.url);
              this.msgSuccess("上传成功");
            }
          }
        });
      },



      handleChange(value) {
        this.form.documentType=  JSON.stringify(this.doc)
        console.log(value);
      },
      getTree(){
        listDept(this.queryParams).then(response => {
          this.deptList = this.handleTree(response.data, "deptId");
          console.log(response.data)
          var datas= response.data
          for(var i=0;i<response.data.length;i++) {
            //i是一级
            if (datas[i].parentId == 100) {

              var datamap={}
              datamap = {
                "value": datas[i].deptName,
                "label": datas[i].deptName,
                "children":[]
              }

              for ( var j = i + 1; j < datas.length; j++) {
                //j是2级
                if (datas[j].parentId == datas[i].deptId) {
                  datamap.children.push({
                    "value": datas[j].deptName,
                    "label": datas[j].deptName,
                  })
                }
              }
              if(datamap.children == ''){
                delete datamap.children;
              }

              this.options.push(datamap)
            }
          }
          this.loading = false;
        });
      },
      /** 查询信息管理列表 */
      getList() {
        this.loading = true;
        listMes(this.queryParams).then(response => {
          //  alert(response.total)
          this.mesList = response.rows;
          this.total = response.total;
          this.loading = false;
          var doc="";
          console.log(this.mesList)
          //str.replace(/\[|]/g, '');
          for (var i=0;i<this.mesList.length;i++){
            doc=this.mesList[i].documentType
            doc.replace(/\[|]/g, '');
            console.log(doc)
            console.log( doc.replace(/\[|]/g, ''))
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.form.documentType = [];
        this.doc = [];
        this.options= [];

      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          tatle: undefined,
          documentType: [],
          img: undefined,
          putFilePath: undefined,
          fileDetails: undefined,
          xsState: undefined,
          typeId: undefined,
          flg: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined,
        };
        this.doc = [];
        this.options= [];
        this.resetForm("form");
        this.fujianName = '';
        this.fujianPath = '';
        this.imgPath='';
        this.receiverName = '';
        this.receiverAccount = '';
        this.mail.oldFileList = [];
        this.mail.fileList = [];
        this.img.oldFileList=[];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.getTree();
        this.reset();
        this.open = true;
        this.title = "添加信息管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.getTree();
        this.reset();
        const id = row.id || this.ids
        //console.log(this.$route.query.id);
        // const mailGuid = this.$route.query.id
        getMes(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改信息管理";
          this.doc = JSON.parse(this.form.documentType)
          this.form = response.data;
          this.status = response.data.status;
          this.fujianPath = response.data.putFilePath;
          this.fujianName = response.data.remark;
          this.imgPath=response.data.img;
          if (this.imgPath!=""){
            this.imgPath+=",";
          }
          if (this.fujianPath != "")
            this.fujianPath += ",";
          if (this.fujianName != "")
            this.fujianName += ",";
          let fujianPathArr = response.data.putFilePath.split(',')
          let fujianNameArr = response.data.remark.split(',')
          let imgPathArr = response.data.img.split(',')
          if(fujianPathArr!=''&&fujianNameArr!=''){
            for (var i = 0; i < fujianNameArr.length; i++) {
              this.mail.oldFileList.push({
                "name": fujianNameArr[i],
                "url": process.env.VUE_APP_BASE_API + fujianPathArr[i],
              });
            };
          }
          if(imgPathArr!=''&&imgPathArr!="null"){

            for (var i = 0; i < imgPathArr.length; i++) {
              this.img.oldFileList.push({
                "url": process.env.VUE_APP_BASE_API + imgPathArr[i],
              });
              console.log(this.img.oldFileList)
            };
          }
        })
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(this.fujianPath!=null+"," && this.fujianPath!=process.env.VUE_APP_BASE_API){
              this.form.remark = this.fujianName.substring(0, this.fujianName.length - 1);
              this.form.putFilePath = this.fujianPath.substring(0, this.fujianPath.length - 1);
              console.log(this.form.putFilePath)
            }
            if (this.imgPath!=null ){
              this.form.img=this.imgPath.substring(0, this.imgPath.length - 1);

            }
            if (this.form.id != undefined) {
              updateMes(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addMes(this.form).then(response => {
                if (response.code === 200) {
                  this.form.documentType=  JSON.stringify(this.doc)
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除信息管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delMes(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有信息管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportMes(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      },
      /** 附件上传---开始  */
      handleBefore(file) {
        // 上传前可以对要上传文件进行控制
        // if (file.type.indexOf("image/") == -1) {
        //   this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        // }
      },
      // handleSuccess(file, fileInfo) {
      //   console.log(fileInfo);
      //   this.mail.fileList.push({
      //     name: fileInfo.name,
      //     uuid: fileInfo.uid,
      //     url: fileInfo.url
      //   });
      // },
      handlePreview(file) {
        // 预览,一些文件因为格式问题无法预览。推荐使用a标签，src为文件的下载地址，点击即可下载,参照录音
        window.open(file.url);
      },
      handleRemove(file) {
        // 移除
        this.mail.oldFileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            //删除
            this.mail.oldFileList.splice(index, 1)
            let fujianNameArr = this.fujianName.split(',');
            let fujianPathArr = this.fujianPath.split(',');
            //重名
            for (var i = 0; i < fujianPathArr.length; i++) {
              if (process.env.VUE_APP_BASE_API +fujianPathArr[i] == file.url) {
                //放一起的目的是 解决重名引起的 账号和名称不对应 问题
                fujianNameArr.splice(i, 1);
                fujianPathArr.splice(i, 1);
                break;
              }
            }
            this.fujianName = fujianNameArr.join(',');
            this.fujianPath = fujianPathArr.join(',');
            console.log(this.fujianName)
            console.log(this.fujianPath)
          }
        });
      },
      beforeRemove(file, fileList) {

        return this.$confirm(`确定移除 ${ file.name }？`);

      },
      fileRequest(item) {
        let uploadData = new FormData()
        uploadData.append('file',item.file)
        uploadFile(uploadData).then(response => {
          if (response.code === 200) {
            this.fujianName += response.fileName + ',';
            this.fujianPath += response.url + ',';
            this.mail.oldFileList.push({
              name: response.fileName,
              url: process.env.VUE_APP_BASE_API + response.url
            });
            console.log(process.env.VUE_APP_BASE_API + response.url);
            this.msgSuccess("上传成功");
          }
        });
      }
    }
  };
</script>


