<template>
  <tf-dialog
    v-bind="$attrs"
    :visible.sync="dialogFormVisible"
    @closed="onCloded"
    @submit="onSubmit"
    :loading="loading"
    :footer="showFooter"
  >
    <el-form ref="form" :rules="rules" :model="form" label-width="140px" label-position="right">
      <el-form-item label="项目名称">
        <el-select
          clearable
          size="small"
          style="width:100%"
          v-model="projectId"
          maxlength="30"
          show-word-limit
          :disabled="true"
        >
        <el-option v-for="(opt, i) in projectData" :key="`opt${i}`" :value="opt.id" :label="opt.name"></el-option>
        </el-select>
      </el-form-item>
      <el-row v-for="(item, i) in formContent" :key="i">
        <el-col :span="12">
          <el-form-item :label="item[0].label" :prop="item[0].name">
            <el-input
              size="small"
              v-model="form[item[0].name]"
              :maxlength="item[0].maxLength"
              show-word-limit
              :disabled="isDetails"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="item[1].label" :prop="item[1].name">
            <el-input
              clearable
              size="small"
              v-model="form[item[1].name]"
              :maxlength="item[1].maxLength"
              show-word-limit
              :disabled="isDetails || (isEdit && item[1].label == '工程编号')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="隐蔽管线点数量(个)" prop="hpoints">
        <el-input
          clearable
          size="small"
          v-model="form.hpoints"
          maxlength="15"
          show-word-limit
          :disabled="isDetails"
        ></el-input>
      </el-form-item>
      <el-form-item label="工程日期范围">
        <el-row>
          <el-col :span="11">
            <el-date-picker
              clearable
              :disabled="isDetails"
              v-model="form.startDate"
              type="date"
              placeholder="选择开始日期"
              value-format="yyyy-MM-dd"
              size="small"
              :picker-options="sOption"
              @change="sDateChange"
            ></el-date-picker>
          </el-col>
          <el-col :span="1" style="text-align: center">至</el-col>
          <el-col :span="12">
            <el-date-picker
              clearable
              :disabled="isDetails"
              v-model="form.finishDate"
              type="date"
              placeholder="选择结束日期"
              value-format="yyyy-MM-dd"
              size="small"
              :picker-options="eOption"
              @change="eDateChange"
            ></el-date-picker>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="工程简介" prop="proIntroduction">
        <el-input
          size="small"
          type="textarea"
          resize="none"
          v-model="form.proIntroduction"
          maxlength="400"
          show-word-limit
          :disabled="isDetails"
        ></el-input>
      </el-form-item>
      <el-form-item label="附件">
        <el-upload
          :on-success="uploadSuccess"
          v-show="!isDetails"
          :show-file-list="true"
          ref="updataDocx"
          class="upload-demo"
          :headers="uploadHeaders"
          :action="baseAddress"
          :data="fileId"
          multiple
          :before-remove="beforeRemove"
          :on-change="uploadChange"
          :auto-upload="false"
        >
          <el-button size="small" type="primary" slot="trigger">选择文件</el-button>
        </el-upload>
        <p v-show="isEdit"
          style="
                height: 20px;
                font-size: 12px;
                border-bottom: 1px solid #dedede;
                border-top: 1px solid #dedede;
                margin: 0;
                margin-top: 10px;
                line-height: 20px;
              "
        >已上传的文件列表</p>
        <div v-show="isDetails || isEdit" class="hideScrollBar" style="max-height: 120px; overflow-y: scroll; border: 1px solid #dedede; padding-left: 10px; margin-top:10px" >
          <div v-for="(item, i) in fileListData" :key="i" class="text-space" style="height: 20px; line-height: 20px; margin:5px" >
            <el-link :href="fileLinkToStreamDownload(item.id)" type="primary" >{{ item.originalName }}</el-link>
            <el-link v-show="isEdit" type="danger" @click="removeFile(item)">删除</el-link>
          </div>
        </div>
        <p v-if="!fileListData.length" style="text-align: center; height: 20px; font-size: 12px; margin: 0px; line-height: 20px" >暂无附件</p>
      </el-form-item>
    </el-form>  
    <!-- 删除 -->
    <el-dialog title="提示" :visible.sync="deleteFlieDialogVisible" width="30%" append-to-body>
      <div style="display: flex; align-items: center">
        <span
          class="iconfont icondtbz"
          style="font-size: 22px; color: #e6a23c; margin-right: 10px; line-height: 20px"
        ></span>
        确认要删除附件《{{ currentFlie.fileName }}》吗?
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="deleteFlieDialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="removeFlieDatas">确 定</el-button>
      </span>
    </el-dialog>
  </tf-dialog>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import { baseAddress } from '@/utils/request'
import { getProjects } from '../../api/engineer'
import { geteSessionStorage } from '@/utils/auth.ts'

import {
  queryDictionariesId,
  projectDetailsQuery,
  queryPageEnclosure,
  addData,
  changeInfo,
  downloadFile,
  removeEnclosureByIds
} from '../../api/engineer'
import { fromExtent } from 'ol/geom/Polygon'

@Component({ name: 'Detail' })
export default class Detail extends Vue {
  loading: Boolean = false
  get listeners() {
    const { submit, ...rest } = this.$listeners
    return rest
  }
  get uploadHeaders() {
    return { Authorization: 'bearer ' + sessionStorage.getItem('token') }
  }

  get baseAddress() {
    return `${baseAddress}/psjc/sysUploadFile/uploadFile`
  }
  get fileId() {
    return this.updataParamsId
  }

  projectData = []
  projectId = Number(geteSessionStorage('currentPrj'))

  form = {

    prjName: '', //
    prjNo: '', // 50 不能为空
    principal: '', // 50
    kcunit: '', // 50
    tcunit: '', // 4
    sjunit: '', // 50
    jsunit: '', // 4
    ctunit: '', // 50
    sgunit: '', // 50
    constructionCharge: '', // 30
    ecoord: '', // 20
    pcoord: '', // 20
    pllength: '', // 9 0
    plnumber: '', // 9 小数0
    jpoints: '', // 15 0
    epoints: '', // 15 0
    hpoints: '', // 15 0
    startDate: '', // date
    finishDate: '', /// date
    proIntroduction: '', // 10
    createUserName: '',
    createUserId: 0
  }
  formContent = [
    [
      { maxLength: '100', label: '工程名称', name: 'prjName' },
      { maxLength: '20', label: '工程编号', name: 'prjNo' }
    ],
    [
      { maxLength: '25', label: '检测单位', name: 'jcunit' },
      { maxLength: '25', label: '勘察单位', name: 'kcunit' }
    ],
    [
      { maxLength: '25', label: '探测单位', name: 'tcunit' },
      { maxLength: '25', label: '设计单位', name: 'sjunit' }
    ],
    [
      { maxLength: '25', label: '建设单位', name: 'jsunit' },
      { maxLength: '25', label: '监理单位', name: 'ctunit' }
    ],
    [
      { maxLength: '25', label: '施工单位', name: 'sgunit' },
      { maxLength: '30', label: '施工负责人', name: 'constructionCharge' }
    ],
    [
      { maxLength: '20', label: '高程系统', name: 'ecoord' },
      { maxLength: '20', label: '平面坐标系统', name: 'pcoord' }
    ],
    [
      { maxLength: '7', label: '管线总长度(m)', name: 'pllength' },
      { maxLength: '9', label: '管线种类数量(个)', name: 'plnumber' }
    ],
    [
      { maxLength: '15', label: '接边点数(个)', name: 'jpoints' },
      { maxLength: '15', label: '明显管线点数量(个)', name: 'epoints' }
    ]
  ]
  rules = {
    prjNo: [
      { required: true, message: '不能为空', trigger: 'blur' },
      {
        pattern: /^[a-zA-Z0-9]+$/,
        message: '只能输入数字或英文字母',
        trigger: 'blur'
      }
    ],
    pllength: [
      {
        pattern: /^[0-9]+([.]{1}[0-9]{1,2})?$/,
        message: '只能输入正数(小数不能超过两位)',
        trigger: 'change'
      }
    ]
  }
  updataParamsId = {
    itemId: '',
    uploadFileTypeDicId: '',
    uploadItemDictId: ''
  }

  id = ''
  dialogFormVisible = false

  deleteFlieDialogVisible = false

  showFooter = true

  fileList = []

  fileListData = []

  currentFlie: any = {}

  isDetails = false
  isEdit = false

  eOption: any = null
  sOption: any = null

  sDateChange(t) {
    if (!this.form.finishDate) {
      this.form.finishDate = this.form.startDate
    }
    this.eOption = {
        disabledDate: time => {
          time = time.getTime()
          return time < new Date(this.form.startDate).getTime()
        }
      }
  }
  eDateChange(t) {
    if (!this.form.startDate) {
      this.form.startDate = this.form.finishDate
    }
    this.sOption = {
        disabledDate: time => {
          time = time.getTime()
          return time > new Date(this.form.finishDate).getTime()
        }
      }
  }

  uploadSuccess(file, fileList) {
    console.log('上传结束')
    if (file.result[0].flag === 'fail') {
      this.$message.error(fileList.response.result[0].msg)
      let dom = this.$refs['updataDocx'] as any
      dom && dom.clearFiles()
    } else {
      let tipType = this.isEdit ? '修改' : '添加'
      this.dialogFormVisible = false
      this.$message.success(`${tipType}成功`)
      this.resetForm()
      this.$emit('update')
    }
  }
  uploadChange(a, b, c) {
    this.fileList.push(a)
  }
  beforeRemove(file, fileList) {
    return this.$confirm(`确定移除 ${file.name}？`).then(() => {
      let index = this.fileList.findIndex((item) => item.uid === file.uid)
      this.fileList.splice(index, 1)
    })
  }
  fileLinkToStreamDownload(id) {
    console.log('文件路径')
    let res = downloadFile(id)
    return baseAddress + res.url
  }

  async removeFlieDatas() {
    let id = this.currentFlie.id
    let res = await removeEnclosureByIds({ ids: id + '' })
    if (res.code === 1) {
      this.$message({
        showClose: true,
        message: '删除成功',
        type: 'success'
      })
    }
    this.getFileList(this.id)
    this.deleteFlieDialogVisible = false
    this.currentFlie = {}
  }
  // 删除附件
  removeFile(file) {
    console.log('当前附件', file)
    this.currentFlie = file
    this.deleteFlieDialogVisible = true
  }

  async getFileList(id) {
    // 获得字典id
    await this.getParamsId()
    // 获取附件列表
    let params = {
      current: 1,
      size: 999,
      itemId: id,
      uploadFileTypeDicId: this.updataParamsId.uploadFileTypeDicId,
      uploadItemDictId: this.updataParamsId.uploadItemDictId
    }
    let fileRes = await queryPageEnclosure(params)
    console.log('附件数据', fileRes)
    this.fileListData = fileRes.result.records
    Promise.resolve()
  }
  async getParamsId() {
    let uploadFileTypeDicId = await queryDictionariesId({ keys: 'uploadFileType' })
    let uploadItemDictId = await queryDictionariesId({ keys: 'uploadItem' })
    uploadFileTypeDicId = uploadFileTypeDicId.result.uploadFileType
    uploadItemDictId = uploadItemDictId.result.uploadItem
    uploadFileTypeDicId.forEach((v) => {
      if (v.codeValue == 'projectInfoDoc') {
        this.updataParamsId.uploadFileTypeDicId = v.id
      }
    })
    uploadItemDictId.forEach((v) => {
      if (v.codeValue == 'tf_ywpn_prjinfo_w') {
        this.updataParamsId.uploadItemDictId = v.id
      }
    })
  }

  // 添加数据
  addData() {
    this.showFooter = true
    this.isDetails = false
    this.setFormData()
  }

  // 修改数据
  editData(row) {
    console.log('修改数据')
    this.showFooter = true
    this.isDetails = false
    this.isEdit = true
    this.setFormData(row.id)
  }

  // 详情
  showDetail(row) {
    this.showFooter = false
    this.isDetails = true
    this.setFormData(row.id)
  }
  //
  setFormData(id?) {
    this.resetForm()
    if (id) {
      this.getFileList(id).then(_ => {
        projectDetailsQuery(id).then(res => {
          let { prjId, ...el } = res.result
          this.form = el
          this.projectId = Number(prjId)
          this.dialogFormVisible = true
        })
      })
    } else {
      this.dialogFormVisible = true
    }

  }
  // 重置表格数据
  resetForm() {
    for (let key in this.form) {
      this.form[key] = ''
    }
  }
  // 提交
  onSubmit() {
      let form = this.$refs['form'] as any
      form.validate(valid => {
        if (valid) {
          // 判断是否有同名文件
          if (this.fileList.length !== 0) {
            let names = this.fileList.map(file => file.name)
            let uninames = new Set(names)
            if (names.length !== [...uninames].length) { return this.$message.error('请删除同名文件后，再上传附件') }
          }
          // 将文件上传到服务器，先触发beforeUpload事件，对上传的文件进行校验，校验通过后才会上传
          // 获取入库人id和名称
          this.form.createUserId = Number(sessionStorage.getItem('userId'))
          this.form.createUserName = sessionStorage.getItem('username')

          let api = null
          if (this.isEdit) { api = changeInfo } else { api = addData }
          api(this.form).then(res => {
            let tipType = this.isEdit ? '修改' : '添加'
            if (res.code === 1) {
              if (this.fileList.length !== 0) {
                this.updataParamsId.itemId = res.result.id
                // 获得字典id
                this.getParamsId().then(res => {
                  let dom = this.$refs['updataDocx'] as any
                  dom.submit()
                })
              } else {
                this.$emit('update')
                // 最后清空表单
                this.dialogFormVisible = false
                this.$message.success(`${tipType}成功`)
              }
            } else {
              this.$message.success(`${tipType}失败`)
            }
          })
        } else {
          console.log('不能提交!!')
          return false
        }
      })
  }
  onCloded() {
    this.isDetails = false
    this.isEdit = false
    this.id = ''
    this.resetForm()
    let dom = this.$refs['updataDocx'] as any
    this.fileList = []
    dom && dom.clearFiles()
    //
    console.log('关闭')
  }
  mounted() {
    getProjects({ size: 1e3, current: 1 }).then(res => {
      if (res.code == 1) {
        this.projectData = res.result.records
      }
    })
  }
}
</script>

<style>
</style>