<template>
  <el-card shadow="never"
           class="aui-card--fill">
    <div class="mod-demo__epidemicreportuserinfo}">
      <el-form :inline="true"
               :model="dataForm"
               @keyup.enter.native="getDataList()">
        <el-form-item label="姓名"
                      prop="userName"
                      label-width="90px">
          <el-input v-model="dataForm.userName"
                    placeholder="姓名"
                    clearable
                    maxlength="49"
                    @keyup.native="btKeyUpUsername"
                    style="width:200px"></el-input>
        </el-form-item>
        <el-form-item label="身份证"
                      prop="idCard"
                      label-width="90px">
          <el-input v-model="dataForm.idCard"
                    placeholder="身份证"
                    clearable
                    maxlength="49"
                    @keyup.native="btKeyUpIdCard"
                    style="width:200px"></el-input>
        </el-form-item>
        <el-form-item label="手机号"
                      prop="moblie"
                      label-width="70px">
          <el-input v-model="dataForm.mobile"
                    placeholder="手机号"
                    clearable
                    maxlength="11"
                    @keyup.native="btKeyUpMobile"
                    style="width:200px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="getDataList()">{{ $t('query') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="exports()">{{ $t('export') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-upload class="upload-demo"
                     ref="upload"
                     v-loading="uploeadLoeading"
                     :action="uploadUrl"
                     :limit="1"
                     :on-success='uploadSuccess'
                     :on-error='errorExceed'
                     :before-upload='beforeUpload'
                     accept=".xls,.xlsx">
            <el-button type="primary">批量导入</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('demo:epidemicreportuserinfo:delete')"
                     type="danger"
                     @click="deleteHandle()">{{ $t('deleteBatch') }}</el-button>
        </el-form-item>
<!--        <el-form-item>-->
<!--          <el-button type="primary" @click="exportHandle()">{{ $t('export') }}</el-button>-->
<!--        </el-form-item>-->
      </el-form>
      <el-table v-loading="dataListLoading"
                :data="dataList"
                border
                @selection-change="dataListSelectionChangeHandle"
                style="width: 100%;">
        <el-table-column label="序号"
                         header-align="center"
                         align="center"
                         width="50px">
          <template slot-scope="scope">
            {{scope.$index+1}}
          </template>
        </el-table-column>
        <el-table-column prop="userName"
                         label="姓名"
                         header-align="center"
                         show-overflow-tooltip
                         align="center"
                         width="150"></el-table-column>
        <el-table-column prop="idCard"
                         label="身份证号"
                         header-align="center"
                         align="center"
                         width="170"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="mobile"
                         label="联系方式"
                         header-align="center"
                         align="center"
                         width="150"></el-table-column>
        <el-table-column prop="gender"
                         label="性别"
                         header-align="center"
                         align="center"
                         width="80"></el-table-column>
        <el-table-column prop="birthday"
                         label="出生年月"
                         header-align="center"
                         align="center"
                         width="120"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="city"
                         label="县/区"
                         header-align="center"
                         align="center"
                         width="150"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="street"
                         label="街道/乡镇"
                         header-align="center"
                         align="center"
                         width="150"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="community"
                         label="社区/村庄"
                         header-align="center"
                         align="center"
                         width="180"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="gridName"
                         label="网格名称"
                         header-align="center"
                         align="center"
                         width="110"></el-table-column>
        <el-table-column prop="plot"
                         label="小区"
                         header-align="center"
                         align="center"
                         width="180"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="buildingNo"
                         label="楼号"
                         header-align="center"
                         align="center"
                         width="100"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="unit"
                         label="单元号"
                         header-align="center"
                         align="center"
                         width="100"></el-table-column>
        <el-table-column prop="roomNo"
                         label="房间号"
                         header-align="center"
                         align="center"
                         width="100"></el-table-column>
        <el-table-column prop="vaccinationNum"
                         label="已接种"
                         header-align="center"
                         align="center"
                         width="180">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.vaccinationState == '0'" size="small" type="danger">未接种</el-tag>
            <el-tag v-if="scope.row.vaccinationState == '2'" size="small" type="success">接种完成</el-tag>
            <el-tag v-if="scope.row.vaccinationState == '1'" size="small" type="success">第 {{scope.row.vaccinationNum}} 针</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime"
                         label="录入时间"
                         header-align="center"
                         align="center"
                         width="180"></el-table-column>
        <el-table-column :label="$t('handle')"
                         fixed="right"
                         header-align="center"
                         align="center"
                         width="150">
          <template slot-scope="scope">
            <!-- <el-button type="text"
                       size="small"
                       @click="lookHandle(scope.row.id)">{{'查看'}}</el-button> -->
            <el-button type="text"
                       size="small"
                       @click="addOrUpdateHandle(scope.row.infoId)">接种登记</el-button>
            <!--            <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">{{ $t('delete') }}</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="page"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="limit"
                     :total="total"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="pageSizeChangeHandle"
                     @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update ref="addOrUpdate"
                     @refreshDataList="getDataList"
                     :data-form="dataForm"></add-or-update>
      <infoDetail v-if="detailVisible"
                  ref="infoDetail"
                  @refreshDataList="getDataList"></infoDetail>
      <el-dialog title="导出选择"
                 :visible.sync="dialogVisibleExcel"
                 width="30%">
        <div style="text-align: center">
          <el-form inline
                   label-width="90px">
            <el-form-item>
              <el-button type="primary"
                         v-loading="exportTemplate">
                <a :href="`https://epdc-yushan.elinkservice.cn/yushan-personal-admin/goDose.xlsx`"
                   target="_blank"
                   download="接种登记表.xlsx"
                   style="color: #ffffff">{{ $t('exportTemplate1') }}</a>
              </el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="exportHandle()">信息导出</el-button>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="dialogVisibleExcel = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import AddOrUpdate from './regist'
import InfoDetail from './epidemicreportuserinfoDetail'
import qs from 'qs'
import Cookies from 'js-cookie'
export default {
  mixins: [mixinViewModule],

  data () {
    return {
      mixinViewModuleOptions: {
        activatedIsNeed: false,
        getDataListURL: '/sys/epidemicuserinfo/getEpidemicPage',
        getDataListIsPage: true,
        deleteURL: '/sys/epidemicuserinfo',
        deleteIsBatch: true,
        exportURL: '/sys/epidemicuserinfo/export',
        exportErrorInfoURL: '/sys/vaccinationerror/exportError'
      },
      dataForm: {
        infoId: '',
        inoutId: '',
        city: '',
        street: '',
        community: '',
        gridName: '',
        plot: '',
        buildingNo: '',
        unit: '',
        roomNo: '',
        userName: '',
        idCard: '',
        mobile: '',
        gender: '',
        birthday: ''
      },
      publicPath: process.env.BASE_URL,
      pickerBeginDateBefore: {
        disabledDate: (time) => {
          let beginDateVal = this.dataForm.endTime
          if (beginDateVal) {
            return time.getTime() > new Date(beginDateVal + ' 00:00:00').getTime()
          }
        }
      },
      pickerBeginDateAfter: {
        disabledDate: (time) => {
          let EndDateVal = this.dataForm.startTime
          if (EndDateVal) {
            return time.getTime() < new Date(EndDateVal + ' 00:00:00').getTime()
          }
        }
      },
      ids: [],
      options: [],
      outStreetArr: [],
      returnStateArr: [
        { dictValue: 1, dictName: '在本地' },
        { dictValue: 2, dictName: '在外地' }
      ],
      exportTemplate: false,
      uploeadLoeading: false,
      dialogVisibleExcel: false,
      detailVisible: false
    }
  },
  created: function () {
    this.getOptions()
    // 乡镇下拉框赋值
    this.getDailyTypeArrInfo()
    this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/sys/vaccinationinfo/importManualScoreExcel?token=${Cookies.get('token')}`
  },
  components: {
    AddOrUpdate,
    InfoDetail
  },
  watch: {
    ids: function (val) {
      if (val.length === 0) {
        this.dataForm.outCode = ''
      } else {
        this.dataForm.outCode = this.ids[val.length - 1]
      }
    }
  },
  methods: {
    // 查看
    lookHandle (id) {
      this.detailVisible = true
      this.$nextTick(() => {
        this.$refs.infoDetail.dataForm.id = id
        this.$refs.infoDetail.init()
      })
    },
    // 获取乡镇下拉信息(传参：4代表查“街道”)
    getDailyTypeArrInfo () {
      this.$http.get(`/sys/epidemicreportuserinfo/selectStreet/4`).then(({ data: res }) => {
        this.outStreetArr = res
      }).catch(() => { })
    },
    // 乡镇取值变化事件
    selectModel (event) {
      this.outStreetArr.find((item) => {
        if (item.dictValue === event) {
          this.dataForm.outStreet = item.dictValue
        }
      })
    },
    getOptions () {
      this.$http
        .get(`/sys/select/getSysArea`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.options = res.data
        })
        .catch(() => { })
    },
    btKeyUpUsername (e) {
      e.target.value = e.target.value.replace(/[`~!@#$%^&*()_+=<>?:"{}|·~！@#￥%……&*（）——+={}|《》？：“”【】、；‘’，。、]/g, '')
      this.dataForm.userName = e.target.value
    },
    btKeyUpIdCard (e) {
      e.target.value = e.target.value.replace(/[`~!@#$%^&*()_+=<>?:"{}|·~！@#￥%……&*（）——+={}|《》？：“”【】、；‘’，。、]/g, '')
      this.dataForm.idCard = e.target.value
    },
    btKeyUpMobile (e) {
      e.target.value = e.target.value.replace(/[`~!@#$%^&*()_+=<>?:"{}|·~！@#￥%……&*（）——+={}|《》？：“”【】、；‘’，。、]/g, '')
      this.dataForm.mobile = e.target.value
    },
    beforeUpload (file) {
      this.uploeadLoeading = true
    },
    errorExceed (file, fileList) {
      this.uploeadLoeading = false
      this.$message.error('上传失败请重试')
    },
    uploadSuccess (response, file, fileList) {
      this.uploeadLoeading = false
      this.$refs.upload.clearFiles()
      if (response.code !== 0 || (response.data !== null && response.data.length > 0)) {
        this.errordataList = response.data
        if (this.errordataList != null && this.errordataList.length > 0) {
          this.$confirm(response.data, '提示', {
            confirmButtonText: '下载',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            var params = qs.stringify({
              'token': Cookies.get('token'),
              ...this.dataForm
            })
            window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewModuleOptions.exportErrorInfoURL}?${params}`
            this.$message({
              type: 'success',
              message: '下载成功'
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消下载'
            })
          })
        } else {
          this.$message.error(response.msg)
        }
        this.getDataList()
        return
      }
      this.$message({
        message: '导入成功',
        type: 'success',
        duration: 1000,
        onClose: () => {
          this.getDataList()
        }
      })
    },
    returnStateFormat (row, column) {
      if (row.returnState === 1 || row.returnState === '1') {
        return '在本地'
      } else if (row.returnState === 2 || row.returnState === '2') {
        return '在外地'
      } else {
        return ''
      }
    },
    returnriskGradeFormat (row, column) {
      // 1:低风险，2：中风险，3：高风险
      if (row.riskGrade === 1 || row.riskGrade === '1') {
        return '低风险'
      } else if (row.returnState === 2 || row.returnState === '2') {
        return '中风险'
      } else if (row.returnState === 3 || row.returnState === '3') {
        return '高风险'
      } else {
        return ''
      }
    },
    // 打开导出弹框
    exports () {
      this.dialogVisibleExcel = true
    }
  }
}
</script>
