<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="title"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_2"
                    placeholder="请输入关怀类型"
                    v-model="formData.title">
          </el-input>
        </el-form-item>

        <el-form-item label="关怀人员"
                      prop="title"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_2"
                    placeholder="请输入关怀人员"
                    v-model="formData.title">
          </el-input>
        </el-form-item>

        <el-form-item label="电话"
                      prop="title"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_2"
                    placeholder="请输入电话"
                    v-model="formData.title">
          </el-input>
        </el-form-item>
        <el-form-item label="地址"
                      prop="title"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    placeholder="请输入地址"
                    v-model="formData.title">
          </el-input>
        </el-form-item>

        <el-form-item label="关怀事项"
                      prop="target"
                      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.target"></el-input>
        </el-form-item>

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

        <el-form-item label="状态"
                      label-width="150px"
                      prop="serviceMatterList">

          <el-select class="item_width_2"
                     v-model="formData.serviceMatter"
                     placeholder="请选择"
                     clearable>
            <el-option class="item_width_2"
                       v-for="item in stateList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>

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

          <el-upload class="upload-demo"
                     :action="uploadUlr"
                     :data="{customerId:customerId}"
                     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"
                       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"
                 v-if="formType != 'detail'"
                 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详情
      stateList: [
        {
          value: '1',
          label: '已完成'
        },
        {
          value: '2',
          label: '未完成'
        },
      ],

      btnDisable: false,

      activityId: '',
      formData: {
        serviceMatter: '',//服务事项
        serviceMatterList: [],
        unitId: '',//单位ID
        unitIdList: [],
        title: '',//活动标题
        target: '',//活动目标
        content: '',//活动内容
        activityTime: '',//活动时间
        peopleCount: 0,//服务人数
        result: '', //活动结果


      },
      serviceList: [],

      fileList: [
        // {
        //   name: 'food.jpeg',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        // }, {
        //   name: 'food2.jpeg',
        //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
        // }
      ],
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/upload-guide-file',
      dialogImageUrl: '',
      dialogVisible: false

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

  },

  methods: {


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

      //获取服务事项
      await this.loadService()

      this.formType = type
      if (activityId) {
        this.activityId = activityId
        this.formData.id = activityId
        await this.loadFormData()
      } else {

      }
      this.endLoading()

    },



    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.addActivity()
        }

      })

    },
    async addActivity () {
      let url = '/heart/icpartyactivity/save'
      // let url = "http://yapi.elinkservice.cn/mock/245/heart/icpartyactivity/save"


      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
      }



      // if (!isLt2M) {
      //   this.$message.warning('上传模板大小不能超过 5MB!')
      //   return
      // }

      // return false // 返回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.url = res.data.url
        file.type = 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.name;
      console.log(a)
      a.href = file.url;
      a.dispatchEvent(event);


    },

    resetData () {
      this.activityId = ''

      this.formData = {
        serviceMatter: '',//服务事项
        serviceMatterList: [],
        unitId: '',//单位ID
        unitIdList: [],
        title: '',//活动标题
        target: '',//活动目标
        content: '',//活动内容
        activityTime: '',//活动时间
        peopleCount: 0,//服务人数
        result: '', //活动结果

      }
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule () {
      return {
        serviceMatterList: [
          { required: true, message: '服务事项不能为空', trigger: 'blur' }
        ],
        unitIdList: [
          { required: true, message: '单位名称不能为空', trigger: 'blur' },
        ],
        title: [
          { required: true, message: '活动标题不能为空', trigger: 'blur' }
        ],

        target: [
          { required: true, message: '活动目标不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '活动内容不能为空', trigger: 'blur' }
        ],
        activityTime: [
          { required: true, message: '活动时间不能为空', trigger: 'blur' }
        ],
        result: [
          { required: true, message: '活动结果不能为空', trigger: 'blur' }
        ],

        longitude: [
          { required: true, message: '坐标不能为空', trigger: 'blur' }
        ]
      }
    },

  },
  props: {

    unitList: {
      type: Array,
      default: []
    },

    // 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>

