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

        <el-form-item label="录入方式"
                      label-width="150px"
                      style="display: block">
          <el-radio-group v-model="enterType"
                          @change="handleChangeEnterType">

            <el-radio :label="'1'">手动输入</el-radio>
            <el-radio :label="'2'">选择居民</el-radio>

          </el-radio-group>

        </el-form-item>

        <el-form-item label="所属网格"
                      style="display: block"
                      label-width="150px">
          <el-select class="item_width_2"
                     v-model.trim="formData.gridId"
                     placeholder="请选择"
                     :disabled="!isFromResi"
                     clearable>
            <el-option v-for="item in gridList"
                       @click.native="handleSelGrid(item.value)"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="居民"
                      prop="personId"
                      style="display: block"
                      label-width="150px">
          <el-select class="item_width_2"
                     v-model.trim="formData.personId"
                     placeholder="请选择"
                     filterable
                     :disabled="!isFromResi"
                     clearable>
            <el-option v-for="item in personList"
                       @click.native="handleSelPerson(item)"
                       :key="item.demandUserId"
                       :label="item.demandUserName"
                       :value="item.demandUserId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="姓名"
                      prop="name"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_2"
                    placeholder="请输入姓名"
                    clearable
                    :disabled="isFromResi"
                    v-model="formData.name">
          </el-input>

        </el-form-item>

        <el-form-item label="手机号"
                      prop="phone"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_2"
                    placeholder="请输入手机号"
                    clearable
                    :disabled="isFromResi"
                    v-model="formData.phone">
          </el-input>
        </el-form-item>
        <el-form-item label="身份证号"
                      prop="idCard"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_2"
                    placeholder="请输入身份证号"
                    clearable
                    :disabled="isFromResi"
                    v-model="formData.idCard">
          </el-input>
        </el-form-item>

        <el-form-item label="检测时间"
                      style="display: block"
                      prop="checkTime"
                      label-width="150px">
          <el-date-picker class="item_width_2"
                          v-model="formData.checkTime"
                          format="yyyy-MM-dd HH:mm"
                          value-format="yyyy-MM-dd HH:mm"
                          type="datetime"
                          clearable
                          placeholder="选择时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="检测地点"
                      prop="address"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    placeholder="请输入检测地点"
                    clearable
                    v-model="formData.address">
          </el-input>
        </el-form-item>

        <el-form-item label="检测结果"
                      prop="type"
                      label-width="150px"
                      style="display: block">
          <el-radio-group v-model="formData.result">

            <el-radio :label="'1'">阴性</el-radio>
            <el-radio :label="'2'">阳性</el-radio>

          </el-radio-group>
        </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-item label="通知渠道"
                      prop="noticeWay"
                      label-width="150px"
                      style="display: block">
          <el-checkbox-group v-model="formData.noticeWay">
            <el-checkbox key="1"
                         label="1">小程序通知</el-checkbox>
            <el-checkbox key="2"
                         label="2">短信通知</el-checkbox>

          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="通知内容"
                      prop="noticeContent"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    type="textarea"
                    maxlength="1000"
                    show-word-limit
                    :autosize="{ minRows: 4, maxRows: 10 }"
                    clearable
                    placeholder="请输入通知内容"
                    v-model="formData.noticeContent"></el-input>
        </el-form-item>

      </el-form>
    </div>

    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button v-if="formType != 'look'"
                 size="small"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>

  </div>
</template>

<script>

import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import { dateFormats } from '@/utils/index'


let loading // 加载动画
export default {
  data () {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
      enterType: '1',//录入方式1 手动输入  2  选择居民
      isFromResi: false,//是否从已有居民信息中选择

      gridList: [],
      personList: [],

      btnDisable: false,

      natId: '',
      formData: {
        name: '',
        idCard: '',
        phone: '',
        checkTime: '',
        address: '',
        result: '',
        noticeWay: [],
        noticeContent: '',
        attachmentList: []
      },


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


    }
  },
  components: {},
  async mounted () {
    const { user } = this.$store.state
    this.agencyId = user.agencyId
    //获取网格下拉框数据
    await this.loadGrid()
  },

  methods: {

    async initForm (type, natId) {
      this.startLoading()
      this.$refs['ref_form'].resetFields();

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

    },

    handleChangeEnterType (value) {
      this.formData.name = ''
      this.formData.phone = ''
      this.formData.idCard = ''
      this.formData.gridId = ''
      this.formData.personId = ''
      if (value === '2') {
        this.isFromResi = true
      } else {
        this.isFromResi = false
      }

    },

    async loadGrid () {
      const url = "/gov/org/customergrid/gridoption"

      let params = {
        agencyId: this.agencyId
      }

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

      if (code === 0) {
        this.gridList = data

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

    },
    async handleSelGrid (value) {

      const url = "/epmetuser/icresiuser/demandusers"

      let params = {
        agencyId: this.agencyId,
        gridId: value
      }

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

      if (code === 0) {
        this.personList = data

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

    },
    async handleSelPerson (personItem) {
      this.formData.name = personItem.demandUserName
      this.formData.phone = personItem.demandUserMobile
      this.formData.idCard = personItem.idCard


    },


    handleTime () {
      if (!this.formData.remindTime) return
      var startAt = new Date(this.formData.remindTime) * 1000 / 1000;
      if (startAt < Date.now()) {
        this.formData.remindTime = dateFormats('YYYY-mm-dd HH:MM', new Date());
      }
    },


    async loadFormData () {

      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/project/memoConcern'
      const url = '/gov/project/memoConcern'
      let params = {
        id: this.natId,
        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
      }, 5000)
      this.$refs['ref_form'].validate(async (valid, messageObj) => {
        if (!valid) {
          app.util.validateRule(messageObj)
          this.btnDisable = false
        } else {

          await this.addNat()
        }

      })

    },
    async addNat () {
      console.log(this.formData)
      return false

      const regPhone = /^1(3|4|5|6|7|8|9)\d{9}$/; //手机号码
      // if (regPhone.test(this.formData.mobile) === false) {
      //   this.btnDisable = false
      //   this.$message({
      //     type: 'warning',
      //     message: '请输入正确的手机号码'
      //   })
      //   return false;
      // }      

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

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

      } else {
        url = '/gov/project/memoConcern/update'
        // url = "http://yapi.elinkservice.cn/mock/245/gov/project/memoConcern/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
        this.$store.dispatch('setTipsList')
        this.$store.dispatch('setTipsTime')
      } 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]
      const isLt1M = (file.size / 1024 / 1024) < 5
      if (extension !== 'xls'
        && extension !== 'xlsx'
        && extension !== 'doc'
        && extension !== 'docx'
        && extension !== 'pdf') {
        this.$message.error('只能上传word、excel、pdf文件！')
        return false
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return isLt1M

    },

    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.natId = ''

      this.formData = {
        name: '',
        idCard: '',
        phone: '',
        checkTime: '',
        address: '',
        result: '',
        noticeWay: [],
        noticeContent: '',
        attachmentList: []

      }
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
        ],
        checkTime: [
          { required: true, message: '检测时间不能为空', trigger: 'blur' },
        ],

        address: [
          { required: false },
        ],
        result: [
          { required: true },
        ],
        address: [
          { required: false },
        ],
        noticeWay: [
          { required: false },
        ],
        noticeContent: [
          { required: false },
        ],

      }
    },

  },
  props: {



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


<style lang="scss" scoped >
@import "@/assets/scss/modules/management/epidemic.scss";
</style>


