<template>
  <div>
    <Drawer
      ref="dialog"
      width="600px"
      placement="right"
      v-model="isShow"
      title="附件"
      :footer-hide="true"
    >
      <div style="display: flex;align-items: center;">
        <el-select size="small" collapse-tags style="width: 200px;" filterable allow-create clearable v-model="filterTag" placeholder="标签" multiple>
          <el-option v-for="item in ['工程类','资产类']" :value="item" :label="item">
          </el-option>
        </el-select>
        <Button type="primary" style="margin-left: 10px;" @click="isShowModal = true">新增</Button>
      </div>

      <Table stripe style="margin-top: 20px;" size="small" :data="fileData" :columns="table">
      </Table>
    </Drawer>

    <Modal title="新增附件" width="580px" v-model="isShowModal" @on-ok="submit">
            <el-form size="small" label-width="100px">
              <el-form-item label="年份选择">
                <el-date-picker v-model="form.year" value-format="yyyy" style="width: 300px;" placeholder="年份选择" type="year"></el-date-picker>
              </el-form-item>
              <el-form-item label="年限信息">
                <el-input v-model="form.nianxian" style="width: 300px;" placeholder="年限信息"></el-input>
              </el-form-item>
              <el-form-item label="标签">
                <el-select style="width: 300px;" filterable allow-create clearable v-model="form.tag" placeholder="标签">
                  <el-option v-for="item in ['工程类','资产类']" :value="item" :label="item">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="附件">
                <el-upload
                  style="width: 400px"
                  ref="upload"
                  multiple
                  :on-success="successHandle"
                  :before-upload="uploadBefore"
                  :before-remove="beforeRemove"
                  accept=".jpg,.jpeg,.png,.gif,.PDF,.pdf, .doc, .docx, .xls, .xlsx"
                  :action="action"
                  :file-list="fileList"
                  :on-remove="removeHande"
                  :limit="100"
                  :headers="{
                   Authorization: `Bearer ${getToken()}`,
              }"
                >
                  <el-button slot="trigger" size="small" type="primary"
                  >选取文件
                  </el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    <br/>单个文件不能超过50M
                  </div>
                </el-upload>
              </el-form-item>
            </el-form>
    </Modal>
  </div>
</template>

<script>
import { save, index, destroy } from '@/api/system/baseForm'
import { getToken } from '@/utils/auth'

export default {
  props: {},
  data() {
    return {
      filterTag: [],
      isShowModal: false,
      table: [
        {
          key: 'original_name',
          title: '文件名称',
          width: 180,
          render: (h, { row }) => (h('div',[
            h('a',{ class: 'original-name-a', on: { click: () => this.openDownload(row) } },row.response?.original_name)
          ]))
        },
        {
          key: 'tag',
          title: "标签",
          align: 'center',
          render: (h, { row }) => (h('Tag',{
            props: {
              color: 'primary'
            }
          },row.response?.tag))
        },
        {
          key: 'year',
          title: '年份',
          align: 'center',
          render: (h, { row }) => (h('span',row.response?.year))
        },
        {
          key: 'nianxian',
          title: '年限',
          align: 'center',
          render: (h, { row }) => (h('span',row.response?.nianxian))
        },
        {
          key: 'btns',
          title: '操作',
          render: (h,{ row }) => (h('div',[
            h('Button',{ props: { type: 'error',size: 'small' },on: { click: ()=>this.deleteFile(row) } },'删除')
          ]))
        }
      ],
      isShow: false,
      id: '',
      type: '',
      action: process.env.VUE_APP_UPLOAD_API,
      fileList: [],
      lists: [],

      form: {
        year: '',
        tag: '',
        nianxian: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: '请填写名称'
          }
        ],
        upload_id: [
          {
            validator: (rule, value, callback) => {
              if (this.fileList.length > 0) {
                callback()
              } else {
                callback(new Error('请上传文件'))
              }
            },
            message: '请上传文件'
          }
        ]
      },
    }
  },
  methods: {
    getToken,
    show() {
      this.isShow = true
    },
    hidden() {
      this.isShow = false
    },
    init() {
      this.form = {
        year: '',
        tag: '',
        nianxian: '',
      }
    },
    setId(id) {
      if (typeof id == 'number') {
        this.id = id
      } else {
        console.error('error typeof id: ' + typeof id)
      }
    },
    getId() {
      return this.id
    },
    setType(type = 'add') {
      let types = ['add', 'editor']
      if (types.includes(type)) {
        this.type = type
      } else {
        console.warn('Unknown type: ' + type)
      }
    },
    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? ''
        })
      }
      if (typeof key === 'string') {
        this.form[key] = value
      }
      if (!key) {
        this.init()
      }
    },

    //上传
    successHandle(response, file, fileList) {
      this.fileList = fileList
    },
    removeHande(file, fileList) {
      this.fileList = fileList
    },
    uploadBefore(file) {
      console.log(file)
      if ((file.size / 1000) > (50 * 1024)) {
        this.$message({
          type: 'warning',
          message: '上传图片大小超过50M！'
        })
        return false
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm('确认要删除吗？').then(res => {
        destroy({
          table_name: 'assets_atlas_files',
          id: file.response.id
        }).then(_ => true).catch(_ => false)
      })
    },

    async getDetail() {
      const res = await index({
        table_name: 'asset_file_files',
        page: 1,
        page_size: 999,
        filter: [
          {
            key: /\/land/g.test(this.$route.path) ? 'land_id' : 'house_id',
            op: 'eq',
            value: this.id
          }
        ]
      })
      this.lists = res.data.map((item) => {
        return {
          name: item.original_name,
          url: item.url,
          response: item
        }
      })
    },

    submit() {
      Promise.all(this.fileList.map(item => save({
        table_name: 'asset_file_files',
        file_id: item?.response?.id,
        [/\/land/g.test(this.$route.path) ? 'land_id' : 'house_id']: this.id,
        name: item?.response?.name,
        original_name: item?.response?.original_name,
        url: item?.response?.url,
        ...this.form
      }))).then(res => {
        this.$message({
          type: 'success',
          message: '附件上传成功'
        })
        this.getDetail()
        this.isShowModal = false
        this.init()
      })
      // save({
      //   table_name: 'asset_file_files',
      //   file_id: this.fileList[0]?.response?.id,
      //   [/\/land/g.test(this.$route.path) ? 'land_id' : 'house_id']: this.id,
      //   name: this.fileList[0]?.response?.name,
      //   original_name: this.fileList[0]?.response?.original_name,
      //   //TODO: 待修改
      //   url: this.fileList[0]?.response?.url.replace(/:\/\/:\/\//g, '://'),
      //     ...this.form
      // }).then(res => {
      //   this.$message({
      //     type: 'success',
      //     message: '附件上传成功'
      //   })
      //   this.getDetail()
      //   this.isShowModal = false
      //   this.init()
      // })
    },

    openDownload (row) {
      window.open(row.url)
    },
    deleteFile (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        if (row.response?.id) {
          destroy({
            table_name: "asset_file_files",
            id: row.response.id
          }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getDetail()
          })
        }
      })
    }
  },
  computed: {
    fileData () {
      if (this.filterTag.length === 0) return this.lists;
      return this.lists.filter(i => (this.filterTag.find(j => j === i.response?.tag)))
    }
  },
  watch: {
    isShow(val) {
      if (val) {
        this.getDetail()
      } else {
        this.id = ''
        this.type = ''
        this.fileList = []
      }
    },
    isShowModal (val) {
      if (val) {

      } else {
        this.fileList = [];
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}

.img__delete {
  transform: scale(0.8, 0.8);

  position: absolute;
  top: 4px;
  right: 4px;
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: $primaryColor;
}

::v-deep .el-upload--picture-card {
  font-size: 28px;
  color: #8c939d;
  width: 80px !important;
  height: 80px !important;
  line-height: 80px !important;
  text-align: center;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px !important;
  height: 80px !important;
  line-height: 80px !important;
  text-align: center;
}

::v-deep .avatar {
  width: 80px !important;
  display: block;
  border-radius: 6px;
}

::v-deep .el-input__inner {
  text-align: left;
}

</style>
<style>
.original-name-a {
  color: red;
  text-decoration: none;
  transition: all 0.2s;
}

.original-name-a:hover {
  color: red;
  text-decoration: underline;
}
</style>
