<template>
  <!-- 后续事项 -->
  <div class="height_100">
    <el-container>
      <el-header style="display: flex;justify-content: flex-end;">
        <div v-if="$reportPermission(projectId, [0, 1])">
          <el-dropdown trigger="click" split-button type="primary" size="small" @command="handleCommand($event)">
            <span @click="handleClick(1)">添加后续事项</span>
            <el-dropdown-menu slot="dropdown" class="text-align_center">
              <el-dropdown-item command="1">添加后续事项</el-dropdown-item>
              <el-dropdown-item command="2">批量添加后续事项</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>
      <el-main class="height_100">
        <el-table v-loading="tableLoading" :data="tableData" style="width: 100%;" border
          header-row-class-name="custom-table-header" @sort-change="sortChange">

          <el-table-column label="#" align="center" width="80px">
            <template slot-scope="scope">
              <div>
                {{ (queryParams.current - 1) * queryParams.size + scope.$index + 1 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column v-for="item in columnList" :key="item.value" :prop="item.value"
            :render-header="$commonJS.renderHeaderMethods" :label="item.name" sortable="custom" align="center">
            <template slot-scope="scope">
              <div v-if="['name'].includes(item.value)">
                <el-tooltip :content="$commonJS.getColumnData(scope.row, item)" placement="top">
                  <span v-html="$commonJS.getColumnData(scope.row, item)"></span>
                </el-tooltip>
              </div>
              <div v-else v-html="$commonJS.getColumnData(scope.row, item)"></div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="150px">
            <template slot-scope="scope">
              <div>
                <el-dropdown trigger="click" split-button type="primary" size="small"
                  @command="handleCommand1($event, scope.row)">
                  <span @click="edit(scope.row)">{{ scope.row.statusStr == '进行中' && $reportPermission(projectId, [0, 1]) ?
                    '编辑' :
                    '查看' }}</span>
                  <el-dropdown-menu slot="dropdown" class="text-align_center">
                    <el-dropdown-item command="1"
                      v-if="scope.row.statusStr == '进行中' && $reportPermission(projectId, [0, 1])">登记结果</el-dropdown-item>
                    <el-dropdown-item command="2" v-else>查看结果</el-dropdown-item>
                    <el-dropdown-item command="3" divided class="color-red"
                      v-if="$reportPermission(projectId, [0, 1])">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer style="display: flex;justify-content: flex-end;align-items:center;">
        <div>
          <el-pagination background layout="total,prev, pager, next,jumper" :total="total"
            @current-change="handleCurrentChange" :current-page="queryParams.current" :page-size="queryParams.size">
          </el-pagination>
        </div>
      </el-footer>
    </el-container>

    <!-- 编辑、查看后续事项弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" v-if="dialogVisible" :width="type == 1 ? '800px' : '1100px'" :before-close="close">
      <div>
        <addMatter :type="type" :projectId="projectId" :row="row" @dialog="getDialog"></addMatter>
      </div>
    </el-dialog>

    <!-- 登记结果弹窗 -->
    <el-dialog title="登记结果" :visible.sync="registerVisible" :width="registerForm.type == 1 ? '1100px' : '500px'"
      :before-close="closeRegister">
      <div>
        <div style="display:flex;justify-content:flex-end;margin-bottom:10px">
          <el-button type="primary" size="small" v-if="registerForm.type == 2" @click="editRegister">{{
            registerForm.edit ? '保存' : '编辑' }}</el-button>
        </div>

        <el-form :model="registerForm" label-width="100px">
          <el-form-item label="结论：" prop="conclusion">
            <el-input v-if="registerForm.type == 1 || registerForm.edit == true" v-model="registerForm.conclusion"
              type="textarea" autocomplete="off" placeholder="请输入结论"></el-input>
            <span v-else>{{ registerForm.conclusion }}</span>
          </el-form-item>
          <el-form-item label="上传附件：">
            <div v-if="registerForm.systemFileList" class="upload-file">
              <div v-for="(item, index) in registerForm.systemFileList" :key="index"
                style="margin:0;display:flex;justify-content:space-around;">
                <p
                  style="margin:0;width:calc(100% - 40px);overflow: hidden;white-space: nowrap;text-overflow:ellipsis;cursor: pointer">
                  {{ item.name ? item.name + '.' + item.suffix : item.fileName }}</p>
                <Menu :data="item" @delFile="delFile"></Menu>
              </div>
            </div>
            <template>
              <div v-if="registerForm.type == 1 || registerForm.edit == true">
                <myUpload :file-list="registerForm.systemFileList" @on-change="onchangeFile" @on-remove="onRemove"
                  style="height: 185px;" :autoUpload="true"></myUpload>
              </div>
            </template>
          </el-form-item>
        </el-form>
        <p v-if="registerForm.type == 1" style="margin-left:10px">后续事项：</p>
        <addMatter :type="type" :projectId="projectId" :sign="matterSign" @value="getMatter" v-if="registerForm.type == 1">
        </addMatter>
      </div>
      <div slot="footer" class="dialog-footer" v-if="registerForm.type == 1 || registerForm.edit == true">
        <el-button @click="closeRegister">取 消</el-button>
        <el-button type="primary" @click="submitRegister" :loading="btnLoading">确 定</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button @click="closeRegister">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import addMatter from './addMatters.vue'
import Menu from '@/utils/model/menu/index.vue'
export default {
  components: {
    addMatter,
    Menu
  },
  props: ['projectId'],
  data() {
    return {
      // 表格字段
      columnList: [
        {
          name: "名称",
          type: "String",
          value: "name",
        },
        {
          name: "描述",
          type: "String",
          value: "description",
        },
        {
          name: "期限",
          type: "String",
          value: "deadline",
        },
        {
          name: "处理人",
          type: "String",
          value: "handler",
        },
        {
          name: "协办人",
          type: "String",
          value: "synery",
        },
        {
          name: "创建人",
          type: "String",
          value: "createName",
        },
        {
          name: "创建时间",
          type: "DataTime",
          value: "createTime",
        },
        {
          name: "完成时间",
          type: "DataTime",
          value: "finishTime",
        },
        {
          name: "状态",
          type: "String",
          value: "statusStr",
        },
      ],
      // 状态
      status: {},
      // 表格数据
      tableData: [],
      // 表格的loading
      tableLoading: false,
      // 表格高度
      tableHeight: null,
      // 表格分页的信息
      queryParams: {
        size: 10,
        current: 1,
      },
      // 表格总条数
      total: 0,
      //排序字段
      sort: [{ "orderBy": "createTime", "orderType": 1 }],
      // 后续事项的弹窗名
      title: '',
      // 控制后续事项显示关闭
      dialogVisible: false,
      // 后续事项弹窗打开时传的信息
      row: null,
      // 控制登记结果弹窗显示关闭
      registerVisible: false,
      // 登记结果中的给后续事项传的判断值
      matterSign: false,
      // 登记结果弹窗中确定按钮loading
      btnLoading: false,
      // 控制显示后续事项的数量，1一个后续事项2多个后续事项
      type: 1,
      // 登记结果的数据
      registerForm: {
        systemFileList: [],
      },
    }
  },
  mounted() {
    // 获取table栏位
    // this.columnList = await this.$commonJS.getCustomField('projectTask')
    this.getList()
  },
  methods: {
    //设置表格高度
    setHeight() {
      const offsetTop = window.innerHeight - this.$refs.table.$el.offsetTop - 200
      const body = document.querySelector('.el-table__body')
      if (!body) {
        return false
      }
      const offsetBodyHeight = body.offsetHeight
      if (this.tableData.length && offsetBodyHeight < offsetTop) {
        this.tableHeight = offsetBodyHeight + 75
      } else if (!this.tableData.length) {
        this.tableHeight = null
      } else {
        this.tableHeight = offsetTop
      }
      this.tableHeight = this.tableHeight > 300 ? this.tableHeight : 300
    },
    // 排序
    sortChange({ column, prop, order }) {
      //如需要多个字段排序，则不需要清空
      var params = {
        sort: this.sort,
        column,
        prop,
        order,
      }
      this.sort = this.$commonJS.getSortData(params)
      this.queryParams.current = 1
      this.getList()
    },
    //查询后续跟进事项
    getList() {
      let params = {
        projectId:this.projectId,
        ...this.queryParams,//分页信息
        // searchQuery: this.$commonJS.objectToString(this.searchOption),//检索条件
        orderDTOList: this.sort,//排序信息
      }
      this.tableLoading = true
      this.$api.getFollowUp(params).then(response => {
        if (response.code == 200) {
          this.tableData = response.data.data
          this.total = response.data.total
          this.tableLoading = false
        }
      }).catch(error => {
        this.tableData = []
        this.total = 0
        this.tableLoading = false
      })
    },
    // 分页
    handleCurrentChange(val) {
      this.queryParams.current = val
      this.getList()
    },
    //新增后续跟进事项的选项
    handleCommand(e) {
      switch (e) {
        case '1':
          this.handleClick(1)
          break;
        case '2':
          this.handleClick(2)
          break;
      }
    },
    //打开新增后续跟进事项弹窗
    handleClick(type) {
      if (type == 1) {
        this.title = '添加后续跟进事项'
      } else if (type == 2) {
        this.title = '批量添加后续跟进事项'
      }
      this.type = type
      this.dialogVisible = true
    },
    //打开编辑后续跟进事项弹窗
    edit(row) {
      this.title = '查看后续跟进事项'
      if (row.statusStr == '进行中') {
        this.title = '编辑后续跟进事项'
      }
      this.type = 1
      this.row = JSON.parse(JSON.stringify(row))
      console.log(this.row,row);
      this.dialogVisible = true
    },
    //关闭弹窗
    close() {
      this.row = null
      // this.type = null
      this.dialogVisible = false
    },
    //获取弹窗状态
    getDialog(val) {
      this.close()
      this.getList()
    },
    //表格下拉菜单
    handleCommand1(e, row) {
      switch (e) {
        case '1'://登记结果
          this.registerResult(row, 1)
          break;
        case '2'://查看结果
          this.registerResult(row, 2)
          break;
        case '3'://删除表格数据
          this.deleteRegister(row)
          break;
      }
    },
    //打开登记结果弹窗
    registerResult(row, type) {
      this.type = 2
      this.registerForm = JSON.parse(JSON.stringify(row))
      this.registerForm.type = type
      if (!this.registerForm.systemFileList) {
        this.$set(this.registerForm, 'systemFileList', [])
      }
      this.registerVisible = true
    },
    //获取需要删除的事项
    deleteRegister(row) {
      if (row) {
        var ids = [row.id]
      } 
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteMatters(ids)
      }).catch(() => {
        this.$message.info('取消操作')
      });

    },
    //删除事项
    deleteMatters(ids) {
      this.$api.deleteFollowUp(ids).then(response => {
        if (response.code == 200) {
          this.$message.success('删除成功')
          this.getList()
        }
      }).catch(error => {
        this.$message.error('删除失败')
      })
    },


    // 上传的文件监听
    onchangeFile(file, fileList) {
      if (file.guid) {
        let index = this.registerForm.systemFileList.findIndex(item => {
          return item.uid == file.uid
        })
        if (index != -1) {
          this.registerForm.systemFileList.splice(index, 1, file)
        }
      } else {
        this.registerForm.systemFileList.push(file.raw)
      }

    },
    // 删除上传的文件
    onRemove(file, fileList) {
      let index = this.registerForm.systemFileList.findIndex(item => {
        return item.uid == file.uid
      })
      if (index != -1) {
        this.registerForm.systemFileList.splice(index, 1)
      }
    },
    //查看未上传的文件
    handlePreview(file) {
      var item = {
        name: file.name,
        suffix: '',
        downLoad: true
      }
      var index = file.raw.type.lastIndexOf('/')
      var type = file.raw.type.substring(index + 1, file.raw.type.length)
      var arr = ['png', 'jpeg', 'bmp', 'jpg']
      if (arr.includes(type)) {
        var FileUrl = URL.createObjectURL(file.raw)
        var isPicture = 1
      } else if (type == 'pdf') {
        var FileUrl = URL.createObjectURL(file.raw)
        var isPicture = 0
      } else {
        return false
      }
      const router = this.$router.resolve({
        path: '/checkFile',
        query: {
          row: JSON.stringify(item),
          FileUrl: FileUrl,
          isPicture: isPicture
        }
      })
      window.open(router.href, '_blank');
    },
    //移除已保存的文件
    delFile(id) {
      var index = this.registerForm.systemFileList.findIndex(item => {
        return item.id == id
      })
      if (index != -1) {
        this.registerForm.systemFileList.splice(index, 1)
        if (this.registerForm.type == 2 && !this.registerForm.edit) {
          this.submitRegister()
        }
      }
    },

    //关闭登记结果弹窗
    closeRegister() {
      // this.type = null
      this.registerForm = {
        systemFileList: []
      }
      if (this.registerForm.type == 1 || this.registerForm.edit) {
        this.$refs.upload.clearFiles()
      }

      this.registerVisible = false
    },
    //获取后续事项
    getMatter(val) {
      this.matterSign = false
      this.btnLoading = true
      try {
        var keyList = {
          name: '',
          description: '',
          handler: '',
          synery: '',
          deadline: ''
        }
        var list = []
        val.forEach(item => {
          var a = false
          for (let key in keyList) {
            if (item[key] != '' && item[key] != null) {
              a = true
            }
          }
          if (a == true) {
            if (item.name != '') {
              list.push(item)
            } else {
              throw new Error()
            }
          }
          console.log(item,a,list);
        })
        if (list.length == 0) {
          return false
        }
        this.registerForm.followUps = list
        this.submitRegister1()
      } catch (e) {
        this.$message.error('后续事项名称不能为空')
        this.registerForm.followUps = [{}]
        this.btnLoading = false
      }
    },
    //编辑事项结果
    editRegister() {
      this.$set(this.registerForm, 'edit', !this.registerForm.edit)
    },
    //更新后续跟进事项结果
    submitRegister() {
      this.matterSign = true
      this.$nextTick(() => {
        // this.btnLoading = true
        if (this.registerForm.followUps && this.registerForm.followUps.length > 0) {
          // this.registerForm.followUps = []
        } else {
          this.submitRegister1()
        }
      })

    },
    // 提交结果，调用api
    submitRegister1() {
      // 判断文件是否都上传完毕
      this.$commonJS.allUploadFile(this.registerForm)
      if (this.registerForm.type == 1) {
        this.registerForm.systemFileList = []
      }
      this.registerForm.followUpId = this.registerForm.id
      this.$api.addRegister(this.registerForm).then(response => {
        if (response.code == 200) {
          this.btnLoading = false
          this.getList()
          if (this.registerForm.type != 2 || this.registerForm.edit) {
            this.closeRegister()
          }

        }
      }).catch(error => {
        this.btnLoading = false
      })
    }
  },
}
</script>