<template>
  <div>
    <el-card :body-style="{ padding: '5px' }" style="margin-bottom:5px">
      <header-box :search="search" @searchClick="searchClick" />
    </el-card>
    <!--<el-card :body-style="{ padding: '10px' }" style="margin-bottom:8px">
      <el-row style="margin-bottom:5px">
        <el-col :span="6">
          <el-button @click="btnOne(1)" type="success" size="mini">新增</el-button>
          <el-button @click="btnOne(2)" type="primary" size="mini">修改</el-button>
          <el-button @click="btnOne(3)" type="danger" size="mini">删除</el-button>
        </el-col>
      </el-row>
      <el-table ref="tableOne" highlight-current-row @row-click="editCurrentApplicationApproval($event)"
        :data="tableDataOne" size="mini" border v-loading="tableOneLoading" max-height="300"
        @selection-change="handleSelectionChange($event,1)">
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="题名" prop="name" align="center"></el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChangeOne" @size-change="handleSizeChangeOne"
        layout="total, prev, pager, next, sizes" :page-size="paginationOne.pageSize" :page-sizes="[10, 20, 40, 150]"
        :current-page="paginationOne.pageNum" :total="paginationOne.total">
      </el-pagination>
    </el-card>
    -->
    <el-card :body-style="{ padding: '10px' }">
      <el-row v-if="showButtons.qxbs" style="margin-bottom:5px;">
        <el-col :span="24" style="text-align: right">
          <el-button @click="btnTwo(1)" type="success" size="mini">新增</el-button>
          <el-button @click="btnTwo(2)" type="primary" size="mini">修改</el-button>
          <el-button @click="btnTwo(3)" type="danger" size="mini">删除</el-button>
        </el-col>
      </el-row>
      <el-table ref="tableTwo" :data="tableDataTwo" size="mini" border v-loading="tableTwoLoading"
        @selection-change="handleSelectionChange($event,2)">
        <el-table-column align="center" type="selection" width="60"></el-table-column>
        <el-table-column align="center" label="原文数量" prop="number" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="opeanDreawer(scope.row)"> {{scope.row.number}}</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" show-overflow-tooltip label="题名" prop="name"></el-table-column>
        <el-table-column align="center" label="创建时间" prop="date" width="250"></el-table-column>
      </el-table>
      <el-pagination @current-change="handleCurrentChangeTwo" @size-change="handleSizeChangeTwo"
        layout="total, prev, pager, next, sizes" :page-size="paginationTwo.pageSize" :page-sizes="[10, 20, 40, 150]"
        :current-page="paginationTwo.pageNum" :total="paginationTwo.total">
      </el-pagination>
    </el-card>
    <!--<el-dialog :title="titleOne" :visible.sync="visibleOne" v-dialogDrag width="35%" :close-on-click-modal="false"
      :before-close="cancel">
      <el-form :model="formOne" ref="ruleFormOne" label-width="80px">
        <el-form-item prop="name" label="题名：" :rules="[{ required: true, message: '题名不能为空'}]">
          <el-input type="textarea" :rows="8" placeholder="请输入内容" v-model="formOne.name">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleFormOne',1)">提交</el-button>
          <el-button @click="resetForm('ruleFormOne')">取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
    -->
    <el-dialog :title="titleTwo" :visible.sync="visibleTwo" v-dialogDrag width="35%" :close-on-click-modal="false"
      :before-close="cancel">
      <el-form :model="formTwo" ref="ruleFormTwo" label-width="80px">
        <el-form-item prop="name" label="题名：" :rules="[{ required: true, message: '题名不能为空'}]">
          <el-input type="textarea" :rows="8" placeholder="请输入内容" v-model="formTwo.name">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleFormTwo',2)">提交</el-button>
          <el-button @click="resetForm('ruleFormTwo',2)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>



    <el-drawer title="原文详情" :visible.sync="drawer" :append-to-body="true" direction="ltr" :before-close="drawerCancel"
      size="100%" :wrapperClosable="false">
      <div class="btnClass" v-if="showButtons.qxbs">
        <el-card :body-style="{ padding: '10px' }">
          <el-button size="mini" type="danger" @click="deletec"> 删除 </el-button>
        </el-card>
      </div>
      <div class="contentBox">
        <el-card :body-style="{ padding: '10px' }" style="width:30%">
          <el-table ref="tableForEach" highlight-current-row border size='mini' :data="tableDataOrigin"
            @row-click="previewImg" tooltip-effect="dark" max-height="800px"
            @selection-change="handleSelectionChangeYW">
            <el-table-column type="selection" width="43"> </el-table-column>
            <el-table-column type="index" width="60" label="序号" align="center">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="fileName" label="文件名称" align="center">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="fileType" label="文件类型" width="90" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center" width="60">
              <template slot-scope="scope">
                <el-button title="下载" type="primary" size="mini" circle @click="Down(scope.row)"
                  icon="el-icon-download"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card :body-style="{ padding: '10px' }" style="width:69%" class="box-card">
          <el-tabs v-model="activeName">
            <el-tab-pane label="查看原文" name="1">
              <!-- 查看原文 -->
              <div class="demo-image__lazy">
                <iframe style="text-align:center" noresize align=center width="100%" height="750px" :src="picUrl"
                  frameborder="0" scrolling="no"></iframe>
              </div>
            </el-tab-pane>
            <el-tab-pane label="添加原文" name="2"  v-if="showButtons.qxbs">
              <div class="uploadBox">
                <el-upload accept="image/jpg,image/jpeg" class="upload-demo" ref="upload" :file-list="fileList"
                  action="#" :auto-upload="false" multiple :on-exceed="beforeAvatarUpload" :on-success="upSuccess"
                  :on-change="handleFileChange" :before-remove="handleFileRemove">
                  <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                  <el-button style="margin-left: 10px" :loading='btnLoading' size="small" type="success"
                    @click="submitUpload">开始上传
                  </el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg文件</div>
                </el-upload>
              </div>
            </el-tab-pane>
            <el-tab-pane label="原文回收站" name="3"  v-if="showButtons.qxbs">
              <el-table :data="backData" style="width: 100%" max-height="350" ref="ytabs" border size="mini">
                <el-table-column prop="fileName" label="文件名称" align="center">
                </el-table-column>
                <el-table-column prop="fileType" label="文件类型" width="150" align="center">
                </el-table-column>
                <el-table-column prop="fileLen" label="文件大小(KB)" align="center">
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" @click="returnContRec(scope.row)">恢复</el-button>
                    <el-button type="text" style="color: #ff0000" @click="delOriRecycle(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>
<script>
  import {
    getDeedsList,
    addDeeds,
    updateDeeds,
    deleteByIds,
    deedsStoryList,
    addDeedsStory,
    updateDeedsStory,
    deleteStoryByIds,
    getDeedsFile,
    moveRecycle,
    RestoreFile,
    deleteFile
  } from "@/api/notice-management.js"
  import {
    getButtonList
  } from "@/api/user"
  import headerBox from './components/header.vue'
  import {
    clearObjValue,
    message
  } from '@/utils/common'
  import {
    URL_PREFIX
  } from "@/utils/url-prefix";
  export default {
    data() {
      return {
        showButtons: {
          qxbs: false,
        },
        search: {
          name: '',
        },
        formOne: {
          name: "",
          id: ""
        },
        formTwo: {
          name: "",
          id: "",
          tid: -1
        },
        titleOne: "新增",
        titleTwo: "新增",
        visibleOne: false,
        visibleTwo: false,
        tableOneLoading: false,
        tableTwoLoading: false,
        tableDataOne: [],
        tableDataTwo: [],
        multipleSelectionOne: [],
        multipleSelectionTwo: [],
        multipleSelectionYW: [],
        paginationOne: {
          pageSize: 10,
          pageNum: 1,
          total: 0,
        },
        paginationTwo: {
          pageSize: 10,
          pageNum: 1,
          total: 0,
        },
        tableOneClickRow: {},
        tableTwoRow: {},
        //抽屉
        activeName: "1",
        drawer: false,
        tableDataOrigin: [],
        tableDataOrigi: [],
        picUrl: "",
        fileList: [],
        backData: [],
        rowTable: {},
        btnLoading: false
      }
    },
    components: {
      headerBox
    },
    methods: {
      Down(val) {
        let str = URL_PREFIX + "/point-strategy/v/DeedsFile/downloadFile?id=" + val.id
        window.location.href = str
      },
      beforeAvatarUpload() {},
      upSuccess() {},
      handleFileRemove() {},
      handleSelectionChangeYW(val) {
        this.multipleSelectionYW = val
      },
      handleSelectionChange(val, key) {
        switch (key) {
          case 1:
            this.multipleSelectionOne = val
            break;
          case 2:
            this.multipleSelectionTwo = val
            break;
        }
      },
      submitForm(formName, key) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            switch (key) {
              /* case 1:
                if (this.titleOne === "新增") {
                  addDeeds(this.formOne).then(res => {
                    message("success", "新增成功", 3000)
                    this.getDataOne()
                    this.cancel()
                    this.$refs[formName].resetFields();
                  })
                } else {
                  updateDeeds(this.formOne).then(res => {
                    message("success", "修改成功", 3000)
                    this.getDataOne()
                    this.cancel()
                    this.$refs[formName].resetFields();
                  })
                }
                break;
              */
              case 2:
                if (this.titleTwo === "新增") {
                  addDeedsStory(this.formTwo).then(res => {
                    message("success", "新增成功", 3000)
                    this.getDataTwo()
                    this.cancel()
                  })
                } else {
                  updateDeedsStory(this.formTwo).then(res => {
                    message("success", "修改成功", 3000)
                    this.getDataTwo()
                    this.cancel()
                  })
                }
                break;
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName, key) {
        this.$refs[formName].resetFields();
        this.cancel()
      },
      editCurrentApplicationApproval(val) {
        this.tableOneClickRow = val
        this.$refs.tableOne.clearSelection();
        this.$refs.tableOne.toggleRowSelection(val);
        this.getDataTwo()
      },
      btnOne(key) {
        switch (key) {
          case 1:
            this.titleOne = "新增"
            this.visibleOne = true
            break;
          case 2:
            if (this.multipleSelectionOne.length != 1) {
              message("warning", "请选择一个文件进行修改", 3000)
              return
            }
            this.formOne.name = this.multipleSelectionOne[0].name
            this.formOne.id = this.multipleSelectionOne[0].id
            this.titleOne = "修改"
            this.visibleOne = true
            break;
          case 3:
            if (!this.multipleSelectionOne.length) {
              message("warning", "请先选择要删除的项目", 4000)
              return
            }
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let arr = this.multipleSelectionOne.map(item => item.id)
              deleteByIds(arr).then(res => {
                message("success", "删除成功", 3000)
                this.getDataOne()
                this.cancel()
              })
            })
            break;
        }
      },
      btnTwo(key) {
        switch (key) {
          case 1:
            this.titleTwo = "新增"
            this.visibleTwo = true
            break;
          case 2:
            if (this.multipleSelectionTwo.length != 1) {
              message("warning", "请选择一个文件进行修改", 3000)
              return
            }
            this.formTwo.name = this.multipleSelectionTwo[0].name
            this.formTwo.id = this.multipleSelectionTwo[0].id
            this.titleTwo = "修改"
            this.visibleTwo = true
            break;
          case 3:
            if (!this.multipleSelectionTwo.length) {
              message("warning", "请先选择要删除的项目", 4000)
              return
            }
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let arr = this.multipleSelectionTwo.map(item => item.id)
              deleteStoryByIds(arr).then(res => {
                message("success", "删除成功", 3000)
                this.getDataTwo()
                this.cancel()
              })
            })
            break;
        }
      },
      getDataOne() {
        let data = {
          limit: this.paginationOne.pageSize,
          page: this.paginationOne.pageNum
        }
        this.tableOneLoading = true
        getDeedsList(data).then(res => {
          this.tableDataOne = res.body.list
          this.paginationOne.total = res.body.total
        }).finally(res => {
          this.tableOneLoading = false
        })
      },
      getDataTwo() {
        this.tableTwoLoading = true
        let data = {
          tid: -1,
          limit: this.paginationTwo.pageSize,
          page: this.paginationTwo.pageNum,
          name: this.search.name,
        }
        deedsStoryList(data).then(res => {
          this.tableDataTwo = res.body.list
          this.paginationTwo.total = res.body.total
        }).finally(res => {
          this.tableTwoLoading = false
        })
      },
      searchClick() {
        this.paginationTwo.pageNum = 1;
        this.getDataTwo()
      },
      cancel() {
        // clearObjValue(this.formOne)
        // clearObjValue(this.formTwo)
        this.formTwo.id = ''
        this.formTwo.name = ''
        this.visibleOne = false
        this.visibleTwo = false
      },

      /* handleCurrentChangeOne(val) {
        this.paginationOne.pageNum = val;
        this.getDataOne()
      },
      handleSizeChangeOne(val) {
        this.paginationOne.pageSize = val;
        this.paginationOne.pageNum = 1;
        this.getDataOne()
      }, */
      handleCurrentChangeTwo(val) {
        this.paginationTwo.pageNum = val;
        this.getDataTwo()
      },
      handleSizeChangeTwo(val) {
        this.paginationTwo.pageSize = val;
        this.paginationTwo.pageNum = 1;
        this.getDataTwo()
      },
      //抽屉
      opeanDreawer(val) {
        this.tableTwoRow = val
        let data = {
          id: val.id
        }
        let p1 = new Promise((resolve, reject) => {
          getDeedsFile({
            ...data,
            status: 1
          }).then(res => {
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        })
        let p2 = new Promise((resolve, reject) => {
          getDeedsFile({
            ...data,
            status: 2
          }).then(res => {
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        })
        Promise.all([p1, p2]).then(res => {
          this.tableDataOrigin = res[0].body.list
          this.backData = res[1].body.list
          this.drawer = true
        })
      },
      handleFileChange(file, fileList) {
        this.fileList = fileList;
      },
      submitUpload() {
        if (!this.fileList.length) {
          message("warning", "请先添加要上传的图片", 3000)
          return
        }
        this.btnLoading = true
        let formData = new FormData();
        // 将上传的文件放到数据对象中 
        this.fileList.forEach(file => {
          formData.append('file', file.raw);
        });
        this.$axios.post(URL_PREFIX + '/point-strategy/v/DeedsFile/addDeedsFile?tId=' + this.tableTwoRow.id,
            formData, {
              headers: {
                'Content-Type': 'multipart/form-data',
                "Token": sessionStorage.getItem('token')
              }
            })
          .then(response => {
            if (response.data.code === "100") {
              this.opeanDreawer(this.tableTwoRow)
              message("success", "上传成功", 2000)
              this.fileList = []
            } else {
              this.$message.error(response.msg);
            }
          })
          .catch(error => {
            this.$message.error('上传失败！');
          }).finally(res => {
            this.btnLoading = false
          });

      },
      drawerCancel() {
        this.getDataTwo()
        this.drawer = false
      },
      deletec() {
        if (!this.multipleSelectionYW.length) {
          message("success", "请选选择要删除的对象", 3000)
          return
        }
        let arr = this.multipleSelectionYW.map(item => item.id)
        this.$confirm('此操作将删除到回收站, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          moveRecycle(arr).then(res => {
            message("success", "成功移除到回收站", 3000)
            this.opeanDreawer(this.tableTwoRow)
            return
          })
        })


      },
      returnContRec(row) {
        row.fileStatus = 1
        RestoreFile(row).then(res => {
          message("success", "恢复成功", 3000)
          this.opeanDreawer(this.tableTwoRow)
        })
      },
      delOriRecycle(row) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteFile({
            id: row.id
          }).then(res => {
            message("success", "删除成功", 3000)
            this.opeanDreawer(this.tableTwoRow)
          })
        })

      },
      previewImg(row) {
        this.rowTable = row
        this.$refs.tableForEach.clearSelection();
        this.$refs.tableForEach.toggleRowSelection(row);
        let name = row.fileNameServer.replace(".jpg", ".pdf")
        this.picUrl = URL_PREFIX + '/point-strategy/v/archiveFile/showImg?fileName=' +
          name + '&path=' + row.filePath + '&data=' + new Date()+'&userId='+sessionStorage.getItem("userid")
        this.activeName = "1"
      },
    },
    created() {
      let btnData = {
        menuid: this.$getMenuId(sessionStorage.getItem("routerIdList"), this.$route.path),
        roleid: sessionStorage.getItem("roleid")
      }
      getButtonList(btnData).then(res => {
        if (res.code === '100') {
          res.body.list.forEach(item => {
            this.showButtons[item.key] = true
          })
        }
      })
      // this.getDataOne()
      this.getDataTwo()

    }
  }

</script>
<style lang="scss" scoped>
  ::v-deep {
    .el-table__body tr.current-row>td {
      background-color: #cbd7ffd4;
      color: #000000;
      font-weight: 600;
    }
  }

  ::v-deep .el-drawer__header {
    margin-bottom: 10px;
    font-weight: 600;
    letter-spacing: 2px;
    font-size: 17px;
  }

  .btnClass {
    padding: 5px;
  }

  .contentBox {
    display: flex;
    justify-content: space-around;

    .box-card {

      .demo-image__lazy {
        background: rgb(245, 245, 245);
        padding: 5px 15px;
        text-align: center;

        .imgs {
          width: 70%
        }
      }

      .uploadBox {
        padding: 5px;

        ::v-deep ul {
          background: rgba(95, 95, 95, 0.2);
          width: 300px;
        }
      }
    }
  }

  ::v-deep .el-drawer__body {
    overflow: auto;
  }

  ::v-deep .el-drawer__container ::-webkit-scrollbar {
    display: none;
  }

  ::v-deep .el-tabs__header {
    margin: 0;
  }

</style>
