<template>
  <div>

    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form"
               :inline="true"
               :model="formData"
               :rules="dataRule"
               :disabled="formType==='detail'"
               class="form">

        <el-form-item label="内容"
                      prop="content"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    type="textarea"
                    maxlength="100"
                    show-word-limit
                    :rows="3"
                    placeholder="请输入内容"
                    v-model="formData.content"></el-input>
        </el-form-item>

        <el-form-item label="解决方式"
                      prop="resolveWay"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    type="textarea"
                    maxlength="100"
                    show-word-limit
                    :rows="3"
                    placeholder="请输入解决方式"
                    v-model="formData.resolveWay"></el-input>
        </el-form-item>

        <el-form-item label="预计处理时间"
                      style="display: block"
                      prop="scheduledTime"
                      label-width="150px">
          <el-date-picker class="item_width_1"
                          v-model="formData.scheduledTime"
                          format="yyyy-MM-dd HH:mm"
                          value-format="yyyy-MM-dd HH:mm"
                          type="datetime"
                          placeholder="选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="提醒时间"
                      style="display: block"
                      prop="remindTime"
                      label-width="150px">
          <el-date-picker class="item_width_1"
                          v-model="formData.remindTime"
                          format="yyyy-MM-dd HH:mm"
                          value-format="yyyy-MM-dd HH:mm"
                          type="datetime"
                          placeholder="选择时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="备注"
                      prop="remark"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    type="textarea"
                    maxlength="100"
                    show-word-limit
                    :rows="3"
                    placeholder="请输入备注"
                    v-model="formData.remark"></el-input>
        </el-form-item>

        <el-form-item class="block"
                      label-width="150px"
                      style="display: block"
                      label="添加附件"
                      prop="attach">

          <el-upload class="upload-demo"
                     :action="uploadUlr"
                     accept=".doc,.pdf,.xls,.docx,.xlsx"
                     :on-success="handleFileSuccess"
                     :on-remove="handleFileRemove"
                     :on-preview="handleFileDownload"
                     :limit="3"
                     :before-upload="beforeUpload"
                     :file-list="fileList">
            <el-button size="small"
                       :disabled="fileList.length==3"
                       type="primary">点击上传</el-button>
            <div slot="tip"
                 class="el-upload__tip">最多三个附件，只能上传word、excel、pdf文件</div>
          </el-upload>
        </el-form-item>

      </el-form>
    </div>

    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button size="small"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'




let loading // 加载动画
export default {
  data () {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情

      btnDisable: false,

      difficultyId: '',
      formData: {
        content: '',//内容	
        resolveWay: '',//解决方式		
        remark: '',//备注	
        scheduledTime: '',//预计处理时间yyyy-mm-dd hh:mm	
        remindTime: '',//提醒时间yyyy-mm-dd hh:mm	
        attachmentList: []
      },


      fileList: [],
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadvariedfile',
      dialogImageUrl: '',
      dialogVisible: false

    }
  },
  components: {},
  mounted () {

  },

  methods: {

    async initForm (type, difficultyId) {
      this.startLoading()
      this.$refs.ref_form.resetFields();

      this.formType = type
      if (difficultyId) {
        this.difficultyId = difficultyId
        this.formData.id = difficultyId
        await this.loadFormData()
      }
      this.endLoading()

    },

    async loadFormData () {

      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/project/memoDifficulty/detail'
      const url = '/gov/project/memoDifficulty/detail'
      let params = {
        id: this.difficultyId,
        readFlag: '0',
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.formData = data

        if (data.attachmentList) {
          data.attachmentList.forEach(element => {
            element.name = element.fileName
            element.type = element.attachmentType
            element.size = element.attachmentSize
          });
          this.fileList = data.attachmentList
        }

      } else {
        this.$message.error(msg)
      }
    },

    async handleComfirm () {
      this.btnDisable = true
      setTimeout(() => {
        this.btnDisable = false
      }, 10000)
      this.$refs['ref_form'].validate((valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj)
          this.btnDisable = false
        } else {

          this.addDifficulty()
        }

      })

    },
    async addDifficulty () {



      if (this.fileList.length > 0) {
        this.formData.attachmentList = this.fileList
      }

      let url = ''
      if (this.formType === 'add') {
        url = '/gov/project/memoDifficulty/save'
        // url = "http://yapi.elinkservice.cn/mock/245/gov/project/memoDifficulty/save"
        this.formData.id = ''

      } else {
        url = '/gov/project/memoDifficulty/update'
        // url = "http://yapi.elinkservice.cn/mock/245/gov/project/memoDifficulty/update"
      }


      const { data, code, msg } = await requestPost(url, this.formData)

      if (code === 0) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.resetData()
        this.$emit('dialogOk')
        this.btnDisable = false
      } else {
        this.btnDisable = false
        this.$message.error(msg)
      }

    },

    handleCancle () {

      this.resetData()
      this.$emit('dialogCancle')

    },

    beforeUpload (file) {
      const array = file.name.split('.')
      const extension = array[array.length - 1]

      if (extension !== 'xls'
        && extension !== 'xlsx'
        && extension !== 'doc'
        && extension !== 'docx'
        && extension !== 'pdf') {
        this.$message.error('只能上传word、excel、pdf文件！')
        return false
      }

    },

    handleFileRemove (file) {

      if (file && file.status === "success") {
        this.fileList.splice(this.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]

        file.fileName = file.name
        file.attachmentUrl = res.data.url
        file.attachmentSize = file.size
        file.attachmentType = 'doc'
        file.attachmentFormat = fileType

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

    //下载
    handleFileDownload (file) {

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


    },

    resetData () {
      this.difficultyId = ''

      this.formData = {
        content: '',//内容	
        resolveWay: '',//解决方式		
        remark: '',//备注	
        scheduledTime: '',//预计处理时间yyyy-mm-dd hh:mm	
        remindTime: '',//提醒时间yyyy-mm-dd hh:mm	
        attachmentList: []

      }
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule () {
      return {
        resiName: [
          { required: true, message: '关怀人员不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '关怀事项不能为空', trigger: 'blur' },
        ],

      }
    },

  },
  props: {



    // serviceList: {
    //   type: Array,
    //   default: []
    // },
  }
}
</script>


<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>
<style  lang="scss" scoped>
.item_width_1 {
  width: 560px;
}
.item_width_2 {
  width: 220px;
}

.text_p {
  margin: 0;
  padding: 0 10px;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  > p {
    margin: 0;
  }
}
</style>

