<template>
  <at-table
    @load="loadData"
    :data="data"
    :page-result="pageResult"
    ref="AtTable"
    :dialogTitle="dialogTitle"
    :dialogVisible="dialogVisible_add"
    :elAuth="'pro_within_edit'"
    @select-all="handleSelect"
    @select="handleSelect"
    @handleDialogCancel="handleDialogCancel"
    @handleDialogClose="handleDialogClose"
    @handleDialogSubmit="handleDialogSubmit"
    @row-dblclick="handleRowDBClick"
  >
    <template v-slot:searchInput>
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        class="search-top"
        @submit.native.prevent
      >
        <el-input
          v-model="searchForm.name"
          style="width: 100%"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="findinfo"
        ></el-input>
        <el-select
          v-model="searchForm.type"
          placeholder="请选择文件类型"
          clearable
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="searchForm.createName"
          style="width: 100%"
          placeholder="请输入上传人"
          clearable
          @keyup.enter.native="findinfo"
        ></el-input>
        <el-button
          size="small"
          @click="findinfo"
          type="primary"
          class="el-icon-search search-btn"
          >查询</el-button
        >
        <el-button
          size="small"
          @click="handleReset"
          type="primary"
          plain
          class="el-icon-refresh"
          >重置</el-button
        >
      </el-form>
    </template>
    <template v-slot:operationBtn>
      <el-button
        size="small"
        type="primary"
        @click="handleAdd"
        icon="el-icon-plus"
        v-methodauth="'pro_within_add'"
        >添加</el-button
      >
      <ht-delete-button
        :url="deleteUrl"
        :requestMethod="'POST'"
        :htTable="$refs.AtTable"
        v-methodauth="'pro_within_del'"
        >删除</ht-delete-button
      >
    </template>
    <template>
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column type="index" label="序号" width="55" align="center">
      </el-table-column>
       <el-table-column
        prop="projectName"
        label="项目名称"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="文件名称"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="type"
        label="文件类型"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{row}">
          <span v-if="row.type == 1">图片</span>
          <span v-if="row.type == 2">文档</span>
          <span v-if="row.type == 3">压缩文件</span>
          <span v-if="row.type == 4">视频</span>
          <span v-if="row.type == 5">其它</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="fileSize"
        label="文件大小"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="createName"
        label="上传人"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="上传时间"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <ht-table-column label="操作" width="200">
        <template v-slot="{row}">
          <el-dropdown
            size="mini"
            split-button
            @command="handleCommand"
            @click="handleCommand({row, command: 'preview'})"
          >
            <span> <i class="el-icon-view"></i>查看</span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                icon="el-icon-download"
                :command="{row: row, command: 'download'}"
                >下载</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </ht-table-column>
    </template>
    <!-- 弹框 -->
    <template v-slot:dialogContent>
      <el-form
        ref="ruleForm"
        data-vv-scope="form"
        :model="form"
        label-width="130px"
        v-if="dialogVisible_add"
        label-position="right"
        v-form
      >
        <el-row>
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="form.projectName"
              placeholder="请选择项目名称"
              @focus="handleFocusProject"
              clearable
            >
              <el-button
                type="primary"
                @click="handleFocusProject"
                slot="append"
                icon="el-icon-search"
              ></el-button>
            </el-input>
          </el-form-item>
        </el-row>
        <file-table
          @handleFile="accessory"
          :file="form.accessory"
          :info="'上传安全巡查记录等文件'"
        />
      </el-form>
    </template>
    <el-dialog
      title="预览"
      class="dialog"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      destroy-on-close
      @close="closeDialog"
      width="100%"
    >
      <div>
        <iframe
          :src="url"
          frameborder="0"
          style="z-index: 1000; height: 800px; width: 100%"
        ></iframe>
      </div>
    </el-dialog>
    <project-within-info-dialog
      ref="project"
      :single="true"
      @select="handleSelectProject"
    ></project-within-info-dialog>
  </at-table>
</template>
<script>
import req from '@/request.js'
import ProjectWithinInfoDialog from '@/components/dialog/ProjectWithinInfoDialog.vue'
export default {
  name: 'ProjectWithinEn',
  components: {
    ProjectWithinInfoDialog,
  },
  data() {
    return {
      loading: false,
      searchForm: {
        name: '',
        type: '',
        createName: '',
      }, //顶部搜索参数
      data: [], //表格数据
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      dialogVisible: false,
      options: [
        {
          value: '1',
          label: '图片',
        },
        {
          value: '2',
          label: '文档',
        },
        {
          value: '3',
          label: '压缩文件',
        },
        {
          value: '4',
          label: '视频',
        },
        {
          value: '5',
          label: '其他',
        },
      ],
      form: {
        accessory: [],
        projectName: '',
        projectId: '',
      },
      dialogVisible_add: false,
      dialogTitle: '添加',
    }
  },
  created() {
    this.$bus.$off('fileAdded')
    this.$bus.$off('fileSuccess')
    this.initProjectAll()
  },
  computed: {
    deleteUrl: function () {
      return window.context.cqxy + '/biz/universal/accessory/v1/delete'
    },
  },
  mounted() {
    // 文件选择后的回调
    this.$bus.$on('fileAdded', () => {
      console.log('文件已选择')
    })
    // 文件上传成功的回调
    this.$bus.$on('fileSuccess', (file) => {
      console.log(file)
      // file.type = 0
      let params = [
        {
          sourceId: 'PlanningEIA',
          projectId: '',
          ...file,
          group: 'PlanningEIA',
        },
      ]
      // this.$http
      //   .post('${cqxy}/biz/universal/accessory/v1/save', params)
      //   .then((res) => {
      //     if (res.data.state) {
      //       this.$message.success(res.data.message)
      //     } else {
      //       this.$message.error(res.data.message)
      //     }
      //     this.$refs.AtTable.load()
      //   })
    })
  },
  methods: {
    handleDialogCancel() {
      this.dialogVisible_add = false
      this.form = {
        accessory: [],
      }
    },
    handleDialogClose() {
      this.handleDialogCancel()
    },
    handleDialogSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.form.accessory.length !== 0) {
          let params = {
            sourceId: 'environmentalManagement', // 'PlanningEIA',
            group: 'environmentalManagement',
          }
          let arr = []
          this.form.accessory.forEach((item) => {
            if (item.id) {
              delete item.id
            }
            arr.push({
              ...params,
              ...item,
              projectId: this.form.projectId,
              projectName: this.form.projectName,
            })
          })

          this.$http
            .post('${cqxy}/biz/universal/accessory/v1/save', arr)
            .then((res) => {
              if (res.data.state) {
                this.$message.success(res.data.message)
                this.dialogVisible_add = false
                this.$refs.$AtTable.load()
              } else {
                this.$message.error(res.data.message)
              }
            })
        } else if (this.form.accessory.length === 0) {
          this.$message.error('至少上传一个附件')
        } else {
          this.$message({
            message: '*号必填项,不能为空!',
            type: 'warning',
          })
          return false
        }
      })
    },
    //获取附件信息
    accessory(info) {
      this.form.accessory = info
    },
    //打开选择项目弹框
    handleFocusProject() {
      this.$refs.project.open()
    },
    //初始获取所有项目数据
    initProjectAll() {
      // /biz/projectManagement/pm/v1/All
      this.$http.post('${cqxy}/biz/projectManagement/pm/v1/noFilterPage').then(
        (res) => {
          this.projectObj = res.data.value.rows
        },
        (error) => {
          reject(error)
        }
      )
    },
    handleSelectProject(data) {
      this.form.projectName = data.projectName
      // this.form.projectCode = data.projectCode
      this.form.projectId = data.id
      this.$refs.ruleForm.clearValidate()
    },
    //重置
    handleReset() {
      this.searchForm.name = ''
      this.searchForm.type = ''
      this.searchForm.createName = ''
      this.$refs['searchForm'].resetFields()
      this.$refs.AtTable.load()
    },
    handleAdd() {
      // this.$bus.$emit('openUploader')
      this.dialogTitle = '添加'
      this.dialogVisible_add = true
      //根据项目id查询
      this.form.projectName = this.projectObj[0].projectName
      // this.form.projectCode = this.projectObj[0].projectCode
      this.form.projectId = this.projectObj[0].id
    },
    handleRowDBClick() {},
    handleSelect(selection) {},
    loadData(param, cb) {
      param.querys = [
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'SOURCE_ID_',
          relation: 'AND',
          value: 'environmentalManagement',
        },
        {
          group: 'advance',
          operation: 'NOTNULL',
          property: 'project_id_',
          relation: 'AND',
          value: '',
        },
         {
          group: 'advance',
          operation: 'NOT_EQUAL',
          parentGroup: '',
          property: 'PROJECT_ID_',
          relation: 'AND',
          value: '',
        },
      ]
        this.$http
          .post('${cqxy}/biz/universal/accessory/v1/getPageBySourceId', param)
          .then(
            (resp) => {
              console.log(resp)
              this.data = resp.data.value.rows
              // this.pageResult.total = resp.data.value.total
              // let response = resp.data.value
              // this.data = response.rows
              this.pageResult = {
                page: resp.data.value.page,
                pageSize: resp.data.value.pageSize,
                total: resp.data.value.total,
              }
            },
            (error) => {
              reject(error)
            }
          )
          .finally(() => {
            if (cb) {
              cb()
            }
          })
    },
    findinfo() {
      let query = [
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'SOURCE_ID_',
          relation: 'AND',
          value: 'environmentalManagement',
          // value: 'PlanningEIA',
        },
      ]
      let search = {
        name_: this.searchForm.name,
        type_: this.searchForm.type,
        create_name_: this.searchForm.createName,
      }
      for (let i in search) {
        if (search[i]) {
          query.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: search[i],
          })
        }
      }
      let data = {
        pageBean: {
          page: 1,
          pageSize: 20,
          showTotal: true,
        },
        querys: query,
      }
      this.$http
        .post('${cqxy}/biz/universal/accessory/v1/getPageBySourceId', data)
        .then((resp) => {
          let response = resp.data.value
          this.data = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total,
          }
        })
    },
    handleCommand(params) {
      console.log(params)
      if (params.command == 'preview') {
        let type = params.row.suffix
        if (
          type.indexOf('xsl') !== -1 ||
          type.indexOf('xslx') !== -1 ||
          type.indexOf('xls') !== -1 ||
          type.indexOf('docx') !== -1 ||
          type.indexOf('doc') !== -1 ||
          type.indexOf('pdf') !== -1 ||
          type.indexOf('jpg') !== -1 ||
          type.indexOf('png') !== -1 ||
          type.indexOf('jpeg') !== -1 ||
          type.indexOf('pptx') !== -1 ||
          type.indexOf('ppt') !== -1
        ) {
          // this.dialogVisible = true
          // // this.url = encodeURIComponent(row.url)
          // this.url = params.row.url
          this.$http
            .get('${cqxy}/wps/oauth/olinePreview?_w_fileid=' + params.row.id)
            .then((res) => {
              let url = window.context.cqxy + res.data.value
              window.open(url, '_blank')
            })
        } else {
          this.$message('当前文件暂不支持预览，请下载查看')
        }
      } else {
        let ids = params.row.id
        let bizPath = 'default'
        let formData = new FormData()
        formData.append('bizPath', bizPath)
        formData.append('ids', ids)
        req
          .downloadPostCopy(
            '${cqxy}/biz/universal/accessory/v1/minIoAllDownFile',
            formData
          )
          .then((res) => {
            console.log(res)
          })
      }
    },
    destroyed() {
      this.$bus.$off('fileAdded')
      this.$bus.$off('fileSuccess')
    },
    closeDialog() {
      this.dialogVisible = false
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/common.scss';
</style>
