<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入事项名称" v-model="listQuery.name"></el-input>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete" @click="delAll">批量删除</el-button>
      <el-button class="filter-item" type="info" icon="el-icon-download" @click="zipQrCode">打包二维码</el-button>
    </div>


    <!-- 查询结果 -->
    <el-table size="small" :data="list" @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column type="selection" width="55px"></el-table-column>

      <el-table-column type="index" label="序号" header-align="center" align="center">
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="事项名称" prop="name">
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="所属事项" prop="parentName">
      </el-table-column>

      <el-table-column align="center" min-width="100px" label="等级" :formatter="formatterLevel" prop="level">
      </el-table-column>


      <el-table-column align="center" min-width="80px" label="图标">
        <template slot-scope="scope" v-if="scope.row.iconStorageUrl">
          <img :src="scope.row.iconStorageUrl" width="30px" height="30px"/>
        </template>
      </el-table-column>

      <el-table-column align="center" width="200px" show-overflow-tooltip label="备注" prop="remark">
      </el-table-column>

      <el-table-column align="center" label="操作" width="400px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="success" size="small" @click="handleCreateItemQrCode(scope.row)">生成二维码</el-button>
          <el-button type="info" size="small" @click="qrcodeDownload(scope.row)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="事项名称" prop="name">
          <el-input v-model="dataForm.name"></el-input>
        </el-form-item>
        <el-form-item label="所属事项">
          <el-input v-model="dataForm.parentName" @focus="changeParent">
            <el-button type="danger" slot="append" @click="clearParentItems">清空</el-button>
          </el-input>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" :rows="2" v-model="dataForm.remark"></el-input>
        </el-form-item>

        <el-form-item v-if="isFirstLevel" label="图标">
          <el-tooltip content="建议图片宽高比100*100" placement="top-start">
            <el-upload
              class="ad-avatar-uploader"
              :action="fileUrl"
              :show-file-list="false"
              :on-success="handleIconSuccess"
              :before-upload="beforeIconUpload">
              <template v-if="dataForm.iconStorageUrl">
                <img :src="dataForm.iconStorageUrl" class="ad-avatar" width="100px" height="100px">
              </template>
              <i v-else class="el-icon-plus ad-avatar-uploader-icon"></i>
            </el-upload>
          </el-tooltip>
        </el-form-item>

        <el-form-item v-if="!isFirstLevel" label="办事指南">
          <el-upload
            :action="fileUrl"
            :file-list="pdfFileList"
            :on-success="handlePdfSuccess"
            :before-upload="beforePdfUpload"
            :on-remove="removePdf">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
          </el-upload>
        </el-form-item>

        <el-form-item v-if="!isFirstLevel" label="表格文档">
          <el-upload
            :action="fileUrl"
            :file-list="tableFileList"
            :on-success="handleTableSuccess"
            :before-upload="beforeTableUpload"
            :on-remove="removeTable">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传pdf,doc和docx格式文件</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择所属事项" :visible.sync="selectParentVisible" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-input
        placeholder="输入关键字进行过滤"
        v-model="filterParentText">
      </el-input>

      <el-tree v-if="!isEmptyTree"
               class="filter-tree"
               :data="itemsParentTreeData"
               :props="defaultProps"
               empty-text="暂无数据"
               default-expand-all
               node-key="id"
               :highlight-current="true"
               :check-on-click-node="true"
               :expand-on-click-node="false"
               :filter-node-method="filterNode"
               @node-click="clickNode"
               ref="itemsParentTree">
      </el-tree>

      <el-row v-if="isEmptyTree">
        <el-col :span="24">
          <div class="tree-empty-text">
            暂无数据
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSelectParentItems">取消</el-button>
        <el-button type="primary" @click="selectParentItems">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 200px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
</style>

<script>
  import { listItems, createItems, detail, updateItems, deleteItems, parentTree,createItemQrCode} from '@/api/items'
  import waves from '@/directive/waves' // 水波纹指令

  export default {
    name: 'items',
    directives: {
      waves
    },
    data() {
      return {
        list: undefined,
        total: undefined,
        listLoading: true,
        multipleSelection: [],
        listQuery: {
          name: '',
          page: 1,
          limit: 20
        },
        dataForm: {
          id: undefined,
          name: undefined,
          parentId: undefined,
          parentName: undefined,
          remark: undefined,
          iconStorageId: undefined,
          iconStorageUrl: undefined,
          pdfStorageId: undefined,
          pdfStorageUrl: undefined,
          tableStorageId: undefined,
          tableStorageUrl: undefined,
          itemsGuidanceDocList: [],
          itemsTableDocList: []
        },
        isFirstLevel: true,
        parentId: undefined,
        parentName: undefined,
        formLevel: 1,
        level: 1,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        selectParentVisible: false,
        rules: {
          name: [{ required: true, message: '事项名称不能为空', trigger: 'blur' }]
        },
        fileUrl: process.env.BASE_API + '/storage/create',
        downloadLoading: false,
        // pdf文件列表
        pdfFileList: [],
        // 表格文档
        tableFileList: [],
        // 过滤树形
        filterParentText: '',
        // 过滤树是否为空
        isEmptyTree: false,
        // 隐藏节点数量
        hideNodeNum: 0,
        itemsParentTreeData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        }
      }
    },
    mounted() {
      this.getList()
    },
    watch: {
      filterParentText(val) {
        this.hideNodeNum = 0
        if (this.$refs.itemsParentTree) {
          this.$refs.itemsParentTree.filter(val)
        }
      },
      hideNodeNum(val) {
        if (this.itemsParentTreeData.length === 0) {
          this.isEmptyTree = true
        } else {
          if (this.hideNodeNum === 0) {
            this.isEmptyTree = false
          } else {
            var length = JSON.stringify(this.itemsParentTreeData).split('id').length - 1
            if (val === length) {
              this.isEmptyTree = true
            }
          }
        }
      }
    },
    methods: {
      getList() {
        this.listLoading = true
        listItems(this.listQuery).then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          name: undefined,
          parentId: undefined,
          parentName: undefined,
          remark: undefined,
          iconStorageId: undefined,
          iconStorageUrl: undefined,
          pdfStorageId: undefined,
          pdfStorageUrl: undefined,
          tableStorageId: undefined,
          tableStorageUrl: undefined,
          itemsGuidanceDocList: [],
          itemsTableDocList: []
        }
        this.pdfFileList = []
        this.tableFileList = []
        this.parentId = undefined
        this.parentName = undefined
        this.level = 1
        this.formLevel = 1
        this.isFirstLevel = true
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const isFirstLevel = this.isFirstLevel
            const iconStorageId = this.dataForm.iconStorageId
            if (isFirstLevel && !iconStorageId) {
              this.$message.error('请上传图标')
              return
            }
            // const pdfStorageId = this.dataForm.pdfStorageId
            // if (!isFirstLevel && !pdfStorageId) {
            //   this.$message.error('请上传pdf文档')
            //   return
            // }
            // const tableStorageId = this.dataForm.tableStorageId
            // if (!isFirstLevel && !tableStorageId) {
            //   this.$message.error('请上传表格文档')
            //   return
            // }
            createItems(this.dataForm).then(response => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })

              this.listQuery.page = 1
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        this.resetForm()
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        this.detail(row.id)
      },
      // 详情
      detail(id) {
        detail(id).then(response => {
          const data = response.data.data
          this.dataForm = data
          if (data.parentId) {
            this.isFirstLevel = false
          }
          this.pdfFileList = []
          if (data.itemsGuidanceDocList) {
            data.itemsGuidanceDocList.forEach(item => {
              this.pdfFileList.push({
                name: item.storageOldName,
                url: item.storageUrl
              })
            })
          }
          this.tableFileList = []
          if (data.itemsTableDocList) {
            data.itemsTableDocList.forEach(item => {
              this.tableFileList.push({
                name: item.storageOldName,
                url: item.storageUrl
              })
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const isFirstLevel = this.isFirstLevel
            const iconStorageId = this.dataForm.iconStorageId
            if (isFirstLevel && !iconStorageId) {
              this.$message.error('请上传图标')
              return
            }
            // const pdfStorageId = this.dataForm.pdfStorageId
            // if (!isFirstLevel && !pdfStorageId) {
            //   this.$message.error('请上传pdf文档')
            //   return
            // }
            // const tableStorageId = this.dataForm.tableStorageId
            // if (!isFirstLevel && !tableStorageId) {
            //   this.$message.error('请上传表格文档')
            //   return
            // }
            updateItems(this.dataForm).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      // 删除
      handleDelete(row) {
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteItems(row.id).then(response => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.listQuery.page = 1
            this.getList()
          })
        }).catch(() => {

        })
      },
      // 批量删除
      delAll() {
        const length = this.multipleSelection.length
        if (length === 0) {
          this.$alert('请至少选择一条要删除的记录', '提示', {
            type: 'warning'
          })
          return
        }
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var ids = []
          for (let i = 0; i < length; i++) {
            ids.push(this.multipleSelection[i].id)
          }
          deleteItems(ids.join(',')).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.multipleSelection = []
            this.getList()
          }).catch(() => {

          })
        }).catch(() => {

        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 图标上传成功
      handleIconSuccess(res) {
        this.dataForm.iconStorageUrl = res.data.url
        this.dataForm.iconStorageId = res.data.key
      },
      // 图标上传
      beforeIconUpload(file) {
        const isJPG = file.type === 'image/jpeg' || 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传图标只能是 JPG、JPEG和PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图标大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },

      // pdf上传成功
      handlePdfSuccess(res) {
        this.dataForm.itemsGuidanceDocList.push({
          docName: res.data.oldName.split('.')[0],
          storageKey: res.data.key
        })
        // this.pdfFileList = []
        this.pdfFileList.push({
          name: res.data.oldName,
          url: res.data.url
        })
      },
      // pdf上传
      beforePdfUpload(file) {
        const isJPG = file.type === 'application/pdf'
        // const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传文件只能是 PDF 格式!')
        }
        // if (!isLt2M) {
        //   this.$message.error('上传图标大小不能超过 2MB!')
        // }
        return isJPG
      },
      // 移除pdf
      removePdf(file, fileList) {
        let index = -1
        this.pdfFileList.forEach((e, ind) => {
          if (e.url === file.url) {
            index = ind
          }
        })
        if (index !== -1) {
          this.pdfFileList.splice(index, 1)
          this.dataForm.itemsGuidanceDocList.splice(index, 1)
        }
      },
      // 表格上传成功
      handleTableSuccess(res) {
        this.dataForm.itemsTableDocList.push({
          docName: res.data.oldName.split('.')[0],
          storageKey: res.data.key
        })
        // this.tableFileList = []
        this.tableFileList.push({
          name: res.data.oldName,
          url: res.data.url
        })
      },
      // 表格上传
      beforeTableUpload(file) {
        const isJPG = file.type === 'application/pdf' || 'application/msword' || 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        // const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传文件只能是 DOC和DOCX 格式!')
        }
        // if (!isLt2M) {
        //   this.$message.error('上传图标大小不能超过 2MB!')
        // }
        return isJPG
      },
      // 移除表格
      removeTable(file, fileList) {
        let index = -1
        this.tableFileList.forEach((e, ind) => {
          if (e.url === file.url) {
            index = ind
          }
        })
        if (index !== -1) {
          this.tableFileList.splice(index, 1)
          this.dataForm.itemsTableDocList.splice(index, 1)
        }
      },
      // 打开所属事件选择框
      changeParent() {
        this.selectParentVisible = true
        this.filterParentText = undefined
        this.hideNodeNum = 0
        this.getItemsParentList()
      },
      // 获取所属事项下拉选项
      getItemsParentList() {
        parentTree().then((res) => {
          this.itemsParentTreeData = res.data.data
          if (!res.data || res.data.length === 0) {
            this.isEmptyTree = true
          } else {
            this.$nextTick(() => {
              this.$refs['itemsParentTree'].setCurrentKey(this.dataForm.parentId)
            })
          }
        }).catch(() => {

        })
      },
      // 清除文本框
      clearParentItems() {
        this.dataForm.parentId = undefined
        this.dataForm.parentName = undefined
        this.parentId = undefined
        this.parentName = undefined
        this.level = 1
        this.formLevel = 1
        this.isFirstLevel = true
      },
      // 过滤节点
      filterNode(value, data) {
        if (value && data.name.indexOf(value) === -1) {
          this.hideNodeNum++
        }
        if (!value) {
          return true
        }
        return data.name.indexOf(value) !== -1
      },
      // 点击节点
      clickNode(node) {
        this.parentId = node.id
        this.parentName = node.name
        this.level = node.level
      },
      // 选择父级事项
      selectParentItems() {
        if (this.isEmptyTree) {
          this.parentId = undefined
          this.parentName = undefined
        } else {
          const currentKey = this.$refs['itemsParentTree'].getCurrentKey()
          if (currentKey === null) {
            this.parentId = undefined
            this.parentName = undefined
          } else {
            if (this.level !== 1) {
              this.$alert('目前只支持选择一级事项', '提示', {
                type: 'warning'
              })
              return
            }
            this.dataForm.parentId = this.parentId
            this.dataForm.parentName = this.parentName
            this.isFirstLevel = false
          }
        }
        this.selectParentVisible = false
      },
      // 取消选择框
      cancelSelectParentItems() {
        this.selectParentVisible = false
        this.parentId = undefined
        this.parentName = undefined
      },
      // 格式化等级列
      formatterLevel(row, column, cellValue, index) {
        return cellValue + '级'
      },

      // 下载二维码
      qrcodeDownload(row) {

        if(row.qrcodeStorageUrl){
            window.location.href = process.env.BASE_API+"/items/downloadItemQrCode?qrcodeStorageId="+row.qrcodeStorageId;
        }else{
          this.$notify({
            title: '提示',
            message: '请先生成二维码',
            type: 'success',
            duration: 2000
          })

        }

      },
      // 生成二维码
      handleCreateItemQrCode(row) {

        createItemQrCode(row.id).then(response => {
          this.$notify({
          title: '成功',
          message: '生成成功',
          type: 'success',
          duration: 2000
          })
          this.getList();
        }).catch(() => {
          this.$notify({
          title: '失败',
          message: '生成失败',
          type: 'error',
          duration: 2000
        })
        })


      },
      // 打包二维码
      zipQrCode() {
        const length = this.multipleSelection.length
        if (length === 0) {
          this.$alert('请至少选择一条记录', '提示', {
            type: 'warning'
          })
          return
        }
        var ids = []
        for (let i = 0; i < length; i++) {
          ids.push(this.multipleSelection[i].id)
        }
        window.location.href = process.env.BASE_API + '/items/downloadZipQrCode?ids=' + ids
      }
    }
  }
</script>
<style>
  .ad-avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .ad-avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .ad-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .ad-avatar {
    display: block;
  }

  .filter-tree {
    margin-top: 20px;
  }

  .tree-empty-text {
    position: absolute;
    left: 50%;
    margin-top: 25px;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    color: #6f7180;
  }
</style>
