<template>
  <div class="epidemic-form">
    <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 v-if="formType==='add'"
                      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 v-if="formType==='add'"
                      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 v-if="formType==='add'"
                      label="居民"
                      prop="userId"
                      style="display: block"
                      label-width="150px">
          <el-select class="item_width_2"
                     v-model.trim="formData.userId"
                     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" style="margin-right:10px;">
          </el-input>
          <el-checkbox v-model="formData.heSuanCheck">添加到核酸检测关注名单</el-checkbox>
        </el-form-item>

        <el-form-item label="手机号"
                      prop="mobile"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_2"
                    placeholder="请输入手机号"
                    clearable
                    :disabled="isFromResi"
                    v-model="formData.mobile">
          </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="现居地"
                      prop="presentAddress"
                      style="display: block"
                      label-width="150px">
          <el-input v-if="isFromResi" class="item_width_2"
                    placeholder="请输入现居地"
                    clearable
                    :disabled="isFromResi"
                    v-model="formData.presentAddress" />
          <el-cascader v-else ref="nowArea" class="item_width_2" :props="areaProps" 
          v-model="nowAllCode" clearable @change="handleNowArea"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址"
                      prop="detailAddress"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_2"
                    placeholder="请输入详细地址"
                    clearable
                    :disabled="isFromResi"
                    v-model="formData.detailAddress">
          </el-input>
        </el-form-item>
        <el-form-item label="来自地区" prop="sourceAddress" style="display: block" label-width="150px">
          <el-cascader ref="sourceArea" v-model="sourceAllCode" class="item_width_2" :props="areaProps"
            @change="handleSourceArea" clearable></el-cascader>
        </el-form-item>

        <el-form-item label="来到本地时间"
                      style="display: block"
                      prop="arriveDate"
                      label-width="150px">
          <el-date-picker class="item_width_2"
                          v-model="formData.arriveDate"
                          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="离开本地时间"
                      style="display: block"
                      prop="leaveDate"
                      label-width="150px">
          <el-date-picker class="item_width_2"
                          v-model="formData.leaveDate"
                          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="remark"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    type="textarea"
                    maxlength="500"
                    show-word-limit
                    :autosize="{ minRows: 4, maxRows: 10 }"
                    clearable
                    placeholder="请输入内容"
                    v-model="formData.remark"></el-input>
        </el-form-item>

        <el-form-item label="通知渠道"
                      prop="channel"
                      label-width="150px"
                      style="display: block">
          <el-checkbox-group v-model="formData.channel">
            <el-checkbox key="0"
                         label="0">小程序通知</el-checkbox>
            <!-- <el-checkbox key="1"
                         label="1">短信通知</el-checkbox> -->

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

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

      </el-form>
    </div>
    <div class="form_div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button v-if="formType != 'detail'"
                 size="small"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm('ref_form')">确 定</el-button>
    </div>

  </div>
</template>

<script>

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

let loading // 加载动画
export default {
  data () {
    let checkMObile = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('手机号不能为空'))
      } else {
        if (!isMobile(value)) {
          callback(new Error('手机号格式不正确'))
        }
        callback()
      }
    }
    let checkIdCard = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('身份证不能为空'))
      } else {
        if (!isCard(value)) {
          callback(new Error('身份证号格式不正确'))
        }
        callback()
      }
    }
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
      hideUploadEdit: false, // 隐藏'上传按钮'
      limitNum: 1,
      enterType: '1',//录入方式1 手动输入  2  选择居民
      isFromResi: false,//是否从已有居民信息中选择

      gridList: [],
      personList: [],

      btnDisable: false,
      sourceAllCode: [], // 来源地全 code
      nowAllCode: [], // 现居地全 code
      icNatId: '',
      formData: {
        gridId: '',
        agencyId: '',//当前网格所属组织Id	
        userId: '',//居民端小程序的用户id、数字社区的icResiUserId、其他情况无值	
        userType: 'icresi',//居民端小程序的人：resi;数字社区的居民：icresi;导入的：import;同步的：synchro	
        name: '',
        idCard: '',
        mobile: '',
        heSuanCheck: false,
        presentAddress: '',
        presentAddressCode: '',
        detailAddress: '',
        sourceAddressCode: '',
        presentAddressPathCode: '',
        sourceAddress: '',
        sourceAddressPathCode: '',
        arriveDate: '',
        remark: '',
        leaveDate: '',
        userType: 'input',
        content: '',
        channel: []

      },
      dataRule: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        idCard: [
          { required: true, validator: checkIdCard, trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: checkMObile, trigger: 'blur' },
        ],
        presentAddress: [
          { required: true, message: '现居地不能为空', trigger: 'blur' },
        ],
        detailAddress: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' },
        ],
        sourceAddress: [
          { required: true, message: '来自地区不能为空', trigger: 'blur' },
        ],
        arriveDate: [
          { required: true, message: '来到本地时间不能为空', trigger: 'blur' },
        ]
      },
      areaProps: {
        lazy: true,
        lazyLoad: this.lzayLoadArea
      }

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

  methods: {
    lzayLoadArea(node, resolve) {
      this.getArea(node, resolve)
      // setTimeout(() => {
        
      // }, 1000)
    },
    async initForm (type, row) {
      console.log('row----', row)
      this.formType = type
      this.formData.agencyId = this.agencyId
      if (type != 'add') {
        this.formData = { ...row, channel: [], content: '' }
        this.sourceAllCode = row.sourceAddressPathCode && row.sourceAddressPathCode.split(',')
        
        if (row.userType == 'icresi') this.isFromResi = true
        else this.nowAllCode = row.presentAddressPathCode && row.presentAddressPathCode.split(',')
      }
      // this.$refs['ref_form'].resetFields();

      console.log('formtype', type)

    },

    handleChangeEnterType (value) {
      this.formData.name = ''
      this.formData.mobile = ''
      this.formData.idCard = ''
      this.formData.gridId = ''
      this.formData.userId = ''
      if (value === '2') {
        this.isFromResi = true
        this.formData.userType = 'icresi'
      } else {
        this.isFromResi = false
        this.formData.userType = 'input'
      }

    },
    handleSourceArea(val) {
      console.log('val-----', val)
      console.log('label-----', this.$refs.sourceArea.getCheckedNodes())
      if (val.length > 0) {
        const labels = this.$refs.sourceArea.getCheckedNodes()[0].pathLabels
        this.formData.sourceAddressCode = val[val.length - 1]
        this.formData.sourceAddress = labels.join('-')
        this.formData.sourceAddressPathCode = val.join(',')
      } else {
        this.formData.sourceAddressCode = ''
        this.formData.sourceAddress = ''
        this.formData.sourceAddressPathCode = ''
      }
      
    },
    handleNowArea(val) {
      console.log('val-----', val)
      console.log('label-----', this.$refs.nowArea.getCheckedNodes())
      if (val.length > 0) {
        const labels = this.$refs.nowArea.getCheckedNodes()[0].pathLabels
        this.formData.presentAddressCode = val[val.length - 1]
        this.formData.presentAddress = labels.join('-')
        this.formData.presentAddressPathCode = val.join(',')
      } else {
        this.formData.presentAddressCode = ''
        this.formData.presentAddress = ''
        this.formData.presentAddressPathCode = ''
      }
    },
    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 getArea (node, resolve) {

      const url = "/commonservice/areacode/nextarea"
      let params = {
        parentLevel: node.data ? node.data.level : '',
        parentAreaCode: node.data ? node.data.code : ''
      }

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

      if (code === 0) {
        const nodes = data.map(item => ({
          value: item.areaCode, // 
          label: item.areaName,
          code: item.areaCode,
          level: item.level,
          leaf: node.level >= 4 // 5层级
        }))
        resolve(nodes)

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

    },
    async handleSelAddress(value) {

      const url = "/gov/org/house/gethouseinfo/" + value

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

      if (code === 0) {
        this.formData.presentAddress = data.agencyPathName
        this.formData.presentAddressCode = data.areaCode
        this.formData.detailAddress = data.allName

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

    },
    async handleSelPerson (personItem) {
      this.formData.userId = personItem.demandUserId
      this.formData.name = personItem.demandUserName
      this.formData.mobile = personItem.demandUserMobile
      this.formData.idCard = personItem.idCard
      this.handleSelAddress(personItem.houseId)
    },

    async loadFormData () {

      // const url = 'http://yapi.elinkservice.cn/mock/245/epmetuser/icNat/detail'
      const url = '/epmetuser/icNat/detail'
      let params = {
        icNatId: this.icNatId,
      }
      const { data, code, msg } = await requestPost(url, params)
      if (code === 0) {
        this.formData = data
        this.formData.icNatId = this.icNatId
        this.fileList = []
        if (data.fileName) {
          let obj = {
            name: data.fileName,
            type: data.attachmentType,
            url: data.attachmentUrl,
          }
          // data.attachmentList.forEach(element => {
          //   element.name = element.fileName
          //   element.type = element.attachmentType
          //   element.size = element.attachmentSize
          // });
          this.fileList.push(obj)

        }

        this.hideUploadEdit = this.fileList.length >= this.limitNum;

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


    async handleComfirm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.formData.channel.length > 0 && !this.formData.content) {
            this.$message({
              type: 'warning',
              message: '请填写通知内容'
            })
            return false;
          }

          this.btnDisable = true
          setTimeout(() => {
            this.btnDisable = false
          }, 5000)

          let url = ''
          if (this.formType === 'add') url = '/epmetuser/tripreport/save'
          else url = '/epmetuser/tripreport/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)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      

    },

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

    },

    handleRemove (file, fileList) {
      this.hideUploadEdit = fileList.length >= this.limitNum;
      this.formData.fileName = ''
      this.formData.attachmentUrl = ''
      this.formData.attachmentType = ''
      this.fileList = []

    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleEditChange (file, fileList) {
      this.hideUploadEdit = fileList.length >= this.limitNum;

    },

    beforeUpload (file) {
      const array = file.name.split('.')
      const extension = array[array.length - 1]
      // const isLt1M = (file.size / 1024 / 1024) < 5
      if (extension !== 'jpg'
        && extension !== 'png'
        && extension !== 'gif'
      ) {
        this.$message.error('只能上传jpg、png、gif文件！')
        return false
      }
      // if (!isLt1M) {
      //   this.$message.error('上传文件大小不能超过 5MB!')
      // }
      // return isLt1M

    },

    handleFileSuccess (res, file) {

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

        this.formData.fileName = file.name
        this.formData.attachmentUrl = res.data.url
        this.formData.attachmentType = 'image'

        file.attachmentFormat = fileType
        file.attachmentSize = file.size

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

    resetData () {
      this.$refs.ref_form.resetFields()
      this.formData.sourceAddressCode = ''
      this.formData.presentAddressCode = ''
      this.formData.sourceAddressPathCode = ''
      this.formData.presentAddressPathCode = ''
      this.sourceAllCode = []
      this.nowAllCode = []
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  }
}
</script>


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

<style lang='scss'>
// 隐藏上传按钮
.hide .el-upload--picture-card {
  display: none;
}
// 添加/删除文件时去掉动画过渡
.el-upload-list__item {
  transition: none !important;
}
</style>



