<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : formType==='detail' ? '查看' : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :disabled="formType==='detail'" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
        <el-form-item label="所属网格"
                      prop="gridId">
            <el-select
                    v-model.trim="dataForm.gridId"
                    placeholder="请选择"
                    clearable
            >
                <el-option
                        v-for="item in optionsG"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                >
                </el-option>
            </el-select>
        </el-form-item>
          <el-form-item label="标题" prop="title">
          <el-input v-model="dataForm.title" placeholder="标题"></el-input>
      </el-form-item>
          <el-form-item label="日志类型" prop="logType">
              <el-select v-model="dataForm.logType"
                         placeholder="请选择"
                         size="small"
                         clearable>
                  <el-option v-for="item in logTypeArr"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
              </el-select>
      </el-form-item>
          <el-form-item label="日志时间" prop="logDate">
              <el-date-picker
                      v-model="dataForm.logDate"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      type="date"
                      placeholder="选择日期">
              </el-date-picker>
      </el-form-item>
          <el-form-item label="内容" prop="content">
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 5 }" v-model="dataForm.content" placeholder="内容"></el-input>
      </el-form-item>
          <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
        <!-- <el-form-item class="block"
                      label="照片"
                      label-width="150px"
                      prop="attach">
            <el-upload class="upload-demo"
                       :action="uploadUlr"
                       accept=".jpg,.png,.jpeg,.bmp"
                       :on-success="handleFileSuccess"
                       :on-remov·e="handleFileRemove"
                       :on-preview="handleFileDownload"
                       :limit="3"
                       :before-upload="beforeUpload"
                       :file-list="dataForm.fileList">
                <el-button size="small"
                           :disabled="dataForm.fileList.length===3"
                           type="primary">点击上传</el-button>
                <div slot="tip"
                     class="el-upload__tip">支持jpg、png、bmp</div>
            </el-upload>
        </el-form-item> -->

        <el-form-item label="照片"
                        style="display:block">
            <el-upload :class="['avatar-uploader', {'hide': hideUploadBtn}] "
                       ref="uploadPic"
                       :action="uploadUlr"
                       list-type="picture-card"
                       :on-exceed="exceedPic"
                       :on-remove="removePic"
                       :file-list="dataForm.fileList"
                       :on-change="handleEditChange"
                       :on-success="handleSuccess"
                       :limit="3">
              <span class="font-14">选择图片</span>
              <div slot="tip"
                   class="upload_tip">最多上传3张图片，图片支持jpg、jpeg、bmp、git或png格式</div>
            </el-upload>
          </el-form-item>
      </el-form>
    <template slot="footer" v-if="formType != 'detail'">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import { requestPost } from "@/js/dai/request"
export default {
  data () {
    return {
      formType: '',
      visible: false,
      gridState: true,
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadvariedfile',
      logTypeArr: [],
      optionsG: [],
      dataForm: {
        id: '',
        agencyId: '',
        pids: '',
        gridId: '',
        title: '',
        logType: '',
        logDate: '',
        content: '',
        remark: '',
        mobile: '',
        fileList: [],
        // imageList: [],//	图片集合
      },
      hideUploadBtn: false
    }
  },
  created () {
    this.getCategrayList()
  },
  computed: {
    dataRule () {
      return {
        title: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        logType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        logDate: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.getGridList()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.dataForm.fileList = []
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/gov/org/icWorkLog/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }

        const grid = this.optionsG.filter(item => item.value === res.data.gridId)
        if (grid.length < 1) {
          this.gridState = false
          this.optionsG.push({label:res.data.gridName, value:res.data.gridId, disabled: true})
        } else {
          this.gridState = true
        }

        const { id } = this.$store.state.user
        if (this.dataForm.createdBy == id) { // 是本人可以修改
          this.formType = 'update'
        } else { // 不是本人只能查看
          this.formType = 'detail'
        }
      }).catch(() => {})
    },
    // 字典
    async getCategrayList () {
      console.log(localStorage.getItem('token'))
      const url = "/sys/dict/data/dictlist"

      let params = {
        dictType: 'log_type'
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.logTypeArr = data
      } else {
        this.$message.error(msg)
      }
    },
    getGridList() {
      this.optionsG = []
      this.$http
        .post('/gov/mine/agency/getmygrids')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            this.optionsG = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    // beforeUpload (file) {
    //   const array = file.name.split('.')
    //   const extension = array[array.length - 1]

    //   const formatarray = ['jpg', 'png', 'jpeg', 'bmp']

    //   if (formatarray.indexOf(extension) === -1) {
    //     this.$message.error('只支持图片、word、pdf')
    //     return false
    //   }

    // },

    // handleFileRemove (file) {

    //   if (file && file.status === "success") {
    //     this.dataForm.fileList.splice(this.dataForm.fileList.findIndex(item => item.uid === file.uid), 1)
    //   }
    // },

    // handleFileSuccess (res, file) {

    //   if (res.code === 0 && res.msg === 'success') {
    //     const array = file.name.split('.')
    //     const fileType = array[array.length - 1]

    //     const picArray = ['jpg', 'png', 'jpeg', 'bmp']
    //     const videoarray = ['mp4', 'wma', 'm4a']
    //     const docArray = ['doc', 'docx', 'xls', 'xlsx', 'pdf']
    //     const mp3Array = ['mp3']

    //     if (picArray.indexOf(fileType) > -1) {
    //       file.attachmentFormat = 'image'
    //     } else if (videoarray.indexOf(fileType) > -1) {
    //       file.attachmentFormat = 'video'
    //     } else if (docArray.indexOf(fileType) > -1) {
    //       file.attachmentFormat = 'doc'
    //     } else if (mp3Array.indexOf(fileType) > -1) {
    //       file.attachmentFormat = 'voice'
    //     }

    //     file.url = res.data.url
    //     file.type = fileType

    //     file.fileName = file.name
    //     file.fileType = file.type

    //     this.dataForm.fileList.push(file)
    //     console.log(this.dataForm.fileList)
    //   } else this.$message.error(res.msg)
    // },
    //下载
    // handleFileDownload (file) {

    //   var a = document.createElement('a');
    //   var event = new MouseEvent('click');
    //   a.download = file.name;
    //   console.log(a)
    //   a.href = file.url;
    //   a.dispatchEvent(event);


    // },

    exceedPic () {
      this.$message.warning("最多上传3张预览图片")

    },
    removePic (file, fileList) {

      // this.formData.imageList.splice(this.formData.imageList.findIndex(item => item === file.url), 1)
      if (file && file.status === "success") {
        this.dataForm.fileList.splice(this.dataForm.fileList.findIndex(item => item.uid === file.uid), 1)
      }
      this.hideUploadBtn = fileList.length >= 3;

    },
    handleSuccess (res, file) {
      if (res.code === 0 && res.msg === 'success') {
          const array = file.name.split('.')
          const fileType = array[array.length - 1]

          const picArray = ['jpg', 'png', 'jpeg', 'bmp']
          const videoarray = ['mp4', 'wma', 'm4a']
          const docArray = ['doc', 'docx', 'xls', 'xlsx', 'pdf']
          const mp3Array = ['mp3']

          if (picArray.indexOf(fileType) > -1) {
            file.attachmentFormat = 'image'
          } else if (videoarray.indexOf(fileType) > -1) {
            file.attachmentFormat = 'video'
          } else if (docArray.indexOf(fileType) > -1) {
            file.attachmentFormat = 'doc'
          } else if (mp3Array.indexOf(fileType) > -1) {
            file.attachmentFormat = 'voice'
          }

          file.url = res.data.url
          file.type = fileType

          file.fileName = file.name
          file.fileType = file.type

          this.dataForm.fileList.push(file)
          console.log(this.dataForm.fileList)
        } else this.$message.error(res.msg)

    },
    // 最多上传3张图，超过时隐藏上传按钮
    handleEditChange (file, fileList) {

      this.hideUploadBtn = fileList.length >= 3;
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      if (!this.gridState) {
        this.dataForm.gridId = ''
        this.gridState = true
        return this.$message.error("请重新选择网格")
      }
      if (this.dataForm.content.length < 70) {
        return this.$message.error("内容不能少于70字")
      }
      if (this.dataForm.fileList.length < 1) {
        return this.$message.error("照片不能为空")
      }
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/gov/org/icWorkLog/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss" scoped>
    .item_width_1 {
        width: 500px;
    }
    .item_width_2 {
        width: 400px;
    }
    .item_width_3 {
        margin-left: 10px;
        width: 200px;
    }
    .item_width_4 {
        width: 200px;
    }

    .div_map {
        margin-top: 10px;
    }

    .div_btn {
        // display: flex;
        // justify-content: flex-end;
    }
    .el-tabs {
        margin: 0 20px;
    }
    .el-upload__tip {
        color: rgb(155, 155, 155);
        margin: 0;
    }
    .form {
        margin-top: 30px;
    }

    .attachement-list {
    }
</style>
