<template>
  <div class="epidemic-form">
    <div class="dialog-h-content scroll-h">

      <el-tabs v-model="activeName"
               type="card"
               class="main_tab"
               @tab-click="handleClick">
        <el-tab-pane label="逐个添加"
                     name="first">
          <el-form ref="ref_form1"
                   :inline="true"
                   :model="formData1"
                   :rules="dataRule1"
                   class="form">

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

            </el-form-item>

            <el-form-item label="手机号"
                          prop="mobile"
                          label-width="150px"
                          style="display: block">
              <el-input class="item_width_2"
                        placeholder="请输入手机号"
                        clearable
                        v-model="formData1.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
                        v-model="formData1.idCard">
              </el-input>
            </el-form-item>
            <el-form-item label="关注原因"
                          prop="reason"
                          label-width="150px"
                          style="display: block">

              <el-input class="item_width_1"
                        placeholder="请输入关注原因"
                        clearable
                        v-model="formData1.reason">
              </el-input>
            </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: 2, maxRows: 5 }"
                        clearable
                        placeholder="请输入通知备注"
                        v-model="formData1.remark"></el-input>
            </el-form-item>

            <el-form-item v-if="false"
                          label="通知渠道"
                          prop="channel"
                          label-width="150px"
                          style="display: block">
              <el-checkbox v-model="formData1.isSelChannel"
                           key="0"
                           label="0">小程序通知</el-checkbox>
              <!-- <el-checkbox-group v-model="formData1.channel">
                <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 v-if="false"
                          label="通知内容"
                          prop="content"
                          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="formData1.content"></el-input>
            </el-form-item>

          </el-form>
        </el-tab-pane>
        <el-tab-pane label="批量添加"
                     name="second">

          <div class="div-mult-table">
            <el-form :inline="true"
                     :model="formDataSearch"
                     ref="ref_formSearch"
                     :label-width="'90px'">
              <el-form-item label="所属网格"
                            label-width="80px">
                <el-select class="item_width_3"
                           v-model.trim="formDataSearch.gridId"
                           placeholder="请选择"
                           size="mini"
                           clearable>
                  <el-option v-for="item in gridList"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="疫苗接种次数小于"
                            label-width="150px">
                <el-input-number class="item_width_3"
                                 v-model="formDataSearch.vaccineCount"
                                 size="mini"
                                 :min="0"
                                 :max="20"
                                 label="疫苗接种次数小于"></el-input-number>
              </el-form-item>
              <el-button style="margin-left:30px"
                         size="mini"
                         class="diy-button--search"
                         @click="handleSearch">查询</el-button>
              <el-button style="margin-left:10px"
                         size="mini"
                         class="diy-button--reset"
                         @click="resetSearch">重置</el-button>
            </el-form>
            <el-table ref="ref_table"
                      class="table"
                      size="mini"
                      :data="tableData"
                      border
                      :height="tableHeight"
                      v-loading="tableLoading"
                      :reserve-selection="true"
                      :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}"
                      @select="handleSelectTable"
                      @select-all="handleSelAll"
                      style="width: 100%">
              <el-table-column type="selection"
                               width="55"></el-table-column>
              <el-table-column label="序号"
                               header-align="center"
                               align="center"
                               type="index"
                               width="50"></el-table-column>

              <el-table-column prop="name"
                               header-align="center"
                               align="center"
                               label="姓名"
                               width="90">
              </el-table-column>
              <el-table-column prop="mobile"
                               header-align="center"
                               align="center"
                               label="手机号"
                               width="110">
              </el-table-column>
              <el-table-column prop="idCard"
                               header-align="center"
                               align="center"
                               label="身份证"
                               min-width="170">
              </el-table-column>
              <el-table-column prop="vaccineCount"
                               header-align="center"
                               align="center"
                               label="疫苗接种次数"
                               min-width="100">
              </el-table-column>

            </el-table>
            <div>
              <el-pagination @size-change="handleSizeChange"
                             @current-change="handleCurrentChange"
                             :current-page.sync="pageNo"
                             :page-sizes="[20, 50, 100, 200]"
                             :page-size="pageSize"
                             layout="sizes, prev, pager, next, total"
                             :total="total">
              </el-pagination>
            </div>

          </div>
          <div class="div-mult-form">

            <!-- <div class="div_person">
              <div class="person_title">已选居民</div>
              <div v-if="selectionAll.length>0">
                <el-tag class="tag_item"
                        v-for="(tag,index) in selectionAll"
                        :key="index"
                        :disable-transitions="false"
                        @close="handleCloseTag(tag,index)"
                        closable>
                  {{tag.name}}
                </el-tag>
              </div>
              <div v-else
                   class="tag_tip">请从列表中选择居民</div>
            </div> -->
            <el-form :inline="true"
                     :model="formData2"
                     ref="ref_form2"
                     :label-width="'90px'">
              <el-form-item label="已选择人数"
                            label-width="100px"
                            style="display: block">
                <span> {{selectionAll.length}}</span>
              </el-form-item>
              <el-form-item label="关注原因"
                            prop="reason"
                            label-width="100px"
                            style="display: block">

                <el-input class="item_width_1"
                          placeholder="请输入关注原因"
                          clearable
                          v-model="formData2.reason">
                </el-input>
              </el-form-item>
              <el-form-item label="备注"
                            prop="remark"
                            label-width="100px"
                            style="display: block">
                <el-input class="item_width_1"
                          type="textarea"
                          maxlength="500"
                          show-word-limit
                          :autosize="{ minRows: 2, maxRows: 5 }"
                          clearable
                          placeholder="请输入通知备注"
                          v-model="formData2.remark"></el-input>
              </el-form-item>

              <el-form-item v-if="false"
                            label="通知渠道"
                            prop="channel"
                            label-width="100px"
                            style="display: block">
                <el-checkbox v-model="formData2.isSelChannel"
                             key="0"
                             label="0">小程序通知</el-checkbox>
                <!-- <el-checkbox-group v-model="formData2.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 v-if="false"
                            label="通知内容"
                            prop="content"
                            label-width="100px"
                            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="formData2.content"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>

    </div>

    <div class="form_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 { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import { mapGetters } from 'vuex'


let loading // 加载动画
export default {
  data () {
    return {

      activeName: "first",

      gridList: [],

      btnDisable: false,

      formDataSearch: {
        gridId: '',
        vaccineCount: undefined,
      },

      formData1: {
        attentionType: 2,
        name: '',
        idCard: '',
        mobile: '',
        reason: '',
        remark: '',
        isSelChannel: false,
        channel: [],
        content: '',

      },

      formData2: {
        attentionType: 2,
        reason: '',
        remark: '',
        isSelChannel: false,
        channel: [],
        content: '',
      },
      tableData: [],
      total: 0,
      pageSize: 20,
      pageNo: 1,
      tableLoading: false,

      selectionAll: [],//选中的人员

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

  methods: {

    async initForm () {

      this.$refs['ref_form1'].resetFields();
      this.$refs['ref_form2'].resetFields();

      await this.loadTable()

    },

    handleSearch () {
      this.loadTable()
    },

    async loadTable () {
      this.tableLoading = true

      const url = "/epmetuser/epidemicPrevention/page"
      // const url = "http://yapi.elinkservice.cn/mock/245/epmetuser/epidemicPrevention/page"
      let params = {
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        ...this.formDataSearch
      }

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

      if (code === 0) {
        this.total = data.total
        data.list.forEach(element => {
          element.isSel = false
        });
        this.tableData = data.list

        this.analysisTableSelection()


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

    handleSelectTable (selection, row) {

      row.isSel = !row.isSel

      if (row.isSel) {
        this.selectionAll.push(row)
      } else {
        for (let i = 0; i < this.selectionAll.length; i++) {
          let item = this.selectionAll[i]
          if (item.idCard === row.idCard) {
            this.selectionAll.splice(i, 1)
            break
          }

        }
      }

    },

    handleSelAll (selection) {
      let selFlag = selection.length > 0//全选选中 还是 全选不选中
      for (let i = 0; i < this.tableData.length; i++) {
        let tableItem = this.tableData[i]
        tableItem.isSel = selFlag
        let isHasItem = false
        for (let j = 0; j < this.selectionAll.length; j++) {
          let selectionItem = this.selectionAll[j]
          if (selectionItem.idCard === tableItem.idCard) {
            isHasItem = true
            if (!selFlag) {
              this.selectionAll.splice(j, 1)
              break
            }
          }

        }

        if (!isHasItem && selFlag) {
          this.selectionAll.push(tableItem)
        }

      }

    },

    //删除标签
    handleCloseTag (tag, index) {
      for (let i = 0; i < this.tableData.length; i++) {

        let tableItem = this.tableData[i]
        if (tag.idCard === tableItem.idCard) {//如果表中存在这个数据
          tableItem.isSel = false
          this.$refs.ref_table.toggleRowSelection(tableItem);
          break
        }

      }

      for (let i = 0; i < this.selectionAll.length; i++) {
        let item = this.selectionAll[i]
        if (item.idCard === tag.idCard) {
          this.selectionAll.splice(i, 1)
          break
        }

      }
    },

    //回显列表选中的行
    analysisTableSelection () {
      this.$nextTick(() => {
        this.tableData.forEach(tableItem => {


          for (let j = 0; j < this.selectionAll.length; j++) {
            let selectionItem = this.selectionAll[j]

            if (selectionItem.idCard === tableItem.idCard) {
              tableItem.isSel = true
              break

            }
          }
          if (tableItem.isSel) {
            this.$refs.ref_table.toggleRowSelection(tableItem);
          }
        });
      })


    },

    handleClick () {

    },

    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)
      }

    },
    handleComfirm () {

      if (this.activeName === 'first') {
        this.$refs['ref_form1'].validate((valid, messageObj) => {
          if (!valid) {
            app.util.validateRule(messageObj)

          } else {
            this.handleVero()
          }

        })

      } else {
        this.handleVero()
      }

    },

    async handleVero () {
      let list = []
      if (this.activeName === 'first') {
        list.push(this.formData1)

        const regPhone = /^1(3|4|5|6|7|8|9)\d{9}$/; //手机号码
        if (regPhone.test(this.formData1.mobile) === false) {
          this.btnDisable = false
          this.$message({
            type: 'warning',
            message: '请输入正确的手机号码'
          })
          return false;
        }
        const regCard = /(^\d{15}$)|(^\d{17}(\d|X)$)/; //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
        if (regCard.test(this.formData1.idCard) === false) {
          this.btnDisable = false
          this.$message({
            type: 'warning',
            message: '请输入正确的身份证号码'
          })
          return false;
        }

        if (this.formData1.isSelChannel) {
          if (!this.formData1.content) {
            this.$message({
              type: 'warning',
              message: '请填写通知内容'
            })
            return false;
          } else {
            this.formData1.channel = ['0']
          }

        } else {
          this.formData1.channel = []
        }

      } else {

        if (this.selectionAll.length === 0) {
          this.$message.info('请选择批量添加的人员')
          return false
        }

        if (this.formData2.isSelChannel) {
          if (!this.formData2.content) {
            this.$message({
              type: 'warning',
              message: '请填写通知内容'
            })
            return false;
          } else {
            this.formData2.channel = ['0']
          }

        } else {
          this.formData2.channel = []
        }

        this.selectionAll.forEach(element => {
          let obj = {
            name: element.name,
            idCard: element.idCard,
            mobile: element.mobile,

            ...this.formData2
          }

          list.push(obj)
        });

      }
      console.log(list)

      this.btnDisable = true
      setTimeout(() => {
        this.btnDisable = false
      }, 5000)
      let url = '/epmetuser/icEpidemicSpecialAttention/vaccination-add'
      // url = "http://yapi.elinkservice.cn/mock/245/gov/project/memoConcern/save"

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

      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')

    },

    resetSearch () {
      this.formDataSearch = {
        gridId: '',
        vaccineCount: undefined,


      }
    },

    destroyed () {
      console.log(11111111)
    },

    resetData () {

      this.formData1 = {
        name: '',
        idCard: '',
        mobile: '',
        reason: '',
        remark: '',
        isSelChannel: false,
        channel: [],
        content: '',
        attentionType: 2,
      }

      this.formData2 = {
        attentionType: 2,
        reason: '',
        remark: '',
        isSelChannel: false,
        channel: [],
        content: '',
      }
      this.formDataSearch = {
        gridId: '',
        vaccineCount: undefined,
      }

      this.selectionAll = []//选中的人员


    },

    handleSizeChange (val) {
      this.pageSize = val
      this.pageNo = 1
      this.loadTable()
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.loadTable()
    },


    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    tableHeight () {
      return 300

    },
    ...mapGetters(['clientHeight', 'iframeHeight']),

    dataRule1 () {

      return {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
        ],




      }
    },

  },
  props: {



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


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


