<template>
  <div class="newly-increased-wrap">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond" ></bread-crumb>
    <div class="component-content screenSet">
      <el-tabs v-model="activeName2" @tab-click="handleTabClick" class="tab-list">
        <el-tab-pane label="单个录入" name="first" class="single-input">
          <el-row class="save-and-add">
            <el-button type="primary" @click="saveEdit">保存并新增</el-button>
          </el-row>
          <edit-information
            ref="newForm"
            :patientInfoObj="patientInfo"
            :checkForm="checkForm"
            @addListenSave="addListenSave"
            :patientId="patientId">
          </edit-information>
        </el-tab-pane>
        <el-tab-pane label="二维码录入" name="second">
          <div class="qr-code-wrap">
            <el-alert
              class="top-tips"
              title="提醒：选择分组后，会自动生成相应的分组二维码，居民扫码后直接进入该分组（若未选择分组，则自动生成未分组二维码，居民扫码后进入默认未分组）"
              type="warning"
              show-icon>
            </el-alert>
            <div class="qr-group">
              <p class="label-name">二维码分组：</p>
              <template v-for="labelItem in currentLabelList">
                <el-tag size="small" :key="labelItem">{{labelItem}}</el-tag> 
              </template>
              <el-tag size="small" class="choose-group" @click="handleChooseGroup">+ 选择分组</el-tag>
            </div>
            <div class="qr-pic-wrap">
              <div class="qr-box">
                <div class="pic">
                  <!-- <vue-qr :text="qrCodeInfo.qrcodeUrl" class="qr-code-img"></vue-qr> -->
                  <canvas id="msg"></canvas>
                  <el-button icon="el-icon-download" class="qr-download-btn" @click="handleQRDownloadModal">下载二维码</el-button>
                </div>  
                <p class="time-limit">有效期：{{qrCodeInfo.beginTime}}-{{qrCodeInfo.endTime}} </p>
                <el-button icon="el-icon-refresh" class="refresh-btn" size="small" @click="handleRefreshCode">刷新有效期</el-button>
              </div>  
            </div>
            <div class="border-space"></div>
            <div class="increased-steps-wrap">
              <div class="label-title">居民添加流程</div>
              <img src="../../../assets/image/patient-add-flow-path.png" alt="" class="flow-path">
            </div>
          </div>
          <!-- 选择分组 弹窗 -->
          <el-dialog
            class="choose-label-wrap"
            title="选择分组"
            :visible.sync="showChooseLabelModal"
            width="680px"
            :close-on-click-modal="false"
            center>
            <p class="under-title-tips">选择分组后，会自动生成相应的分组二维码，居民扫码后直接进入该分组</p>
            <el-row class="row-in-line">
              <el-button size="small" class="clear-select" :disabled="choosedLabelList.length<1" @click="handleClearSelect">清空选择</el-button>
              <el-button type="primary" class="right" size="small" @click="handleGoToLabelManage">分组管理</el-button>
              <p class="tips">未找到分组可去分组管理新建分组</p>
            </el-row>
            <div class="list-wrap">
              <el-checkbox-group v-model="choosedLabelList">
                <template v-for="item in labelNameList" >
                  <el-checkbox v-if="item.labelId != 0" :label="item.labelId" border :key="item.labelId">
                    {{item.labelName}}
                  </el-checkbox>
                </template>
              </el-checkbox-group>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showChooseLabelModal = false" size="small">取 消</el-button>
              <el-button type="primary" @click="handleAfterChooseLabel" size="small">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 重新加载当前分组列表 -->
          <el-dialog
            class="reload-label-modal"
            :visible.sync="showReloadLabelModal"
            width="320px"
            :show-close="false"
            :close-on-click-modal="false"
            center>
            <p class="tips">您刚才跳转到分组管理页面进行新建分组，请点击下方按钮刷新数据</p>
            <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="handleReloadLabel">重新加载</el-button>
            </span>
          </el-dialog>
          <!-- 下载二维码 弹窗 -->
          <el-dialog
            class="download-qr-modal"
            title="下载二维码"
            :visible.sync="showDownloadQRModal"
            width="500px"
            :show-close="false"
            :close-on-click-modal="false"
            center>
            <div class="qr-pic"></div>
            <p class="exp-date">有效期：2019.5.1-2019.5.30</p>
            <div class="choose-group">
              <p class="title">分组：</p>
              <el-select v-model="currentQRDownloadGroup" placeholder="选择分组">
                <el-option
                  v-for="item in qrDownloadGroups"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <p class="under-tips">选择分组后，会自动生成相应的分组二维码，居民扫码后直接进入该分组</p>
            <p class="under-tips">（若未选择分组，则自动生成未分组二维码，居民扫码后进入默认未分组）</p>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showDownloadQRModal = false">取 消</el-button>
              <el-button type="primary" @click="handleGoToDownloadQR">确定下载</el-button>
            </span>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="批量导入" name="third">
          <div class="step-guide">
            <ul class="guide-list">
              <li class="first">
                <div class="procedure">
                  <i class="icon">1</i>
                  <p class="text">下载模板</p>
                  <p class="border"></p>
                </div>
                <div class="under-info">
                  <p class="step-tips">点击下方“下载模板”</p>
                  <el-button type="primary" size="small" @click="handleDownloadDemo">下载模板</el-button>
                </div>
              </li>
              <li class="first second">
                <div class="procedure">
                  <i class="icon">2</i>
                  <p class="text">填写居民信息</p>
                  <p class="border"></p>
                </div>
                <div class="under-info">
                  <p class="step-tips">按照模板编辑居民信息</p>
                  <ul class="fill-tips">
                    <li>
                      <i class="tips-title notice">填写要求：</i>
                    </li>
                    <li>
                      <i class="tips-title">居民姓名：</i>
                      <p>当前支持2~15个字符</p>
                    </li>
                    <li>
                      <i class="tips-title">出生年月：</i>
                      <p>"年-月-日"，我们将优先识别身份证信息中的出生年月信息，若身份证未填，将识别此处信息。</p>
                    </li>
                    <li>
                      <i class="tips-title">居住地址：</i>
                      <p>≤50字</p>
                    </li>
                    <li>
                      <i class="tips-title">电话：</i>
                      <p>请输入11为手机号码</p>
                    </li>
                    <li>
                      <i class="tips-title">分组与诊断：</i>
                      <p>多个分组之间，用中文逗号“，”分割</p>
                    </li>
                  </ul>
                </div>
              </li>
              <li class="first third">
                <div class="procedure">
                  <i class="icon">3</i>
                  <p class="text">上传文件</p>
                </div>
                <div class="under-info">
                  <p class="step-tips">将填写好的居民信息文件在下方进行上传</p>
                  <el-upload
                    class="upload-file"
                    drag
                    :action="uploadUrl"
                    :headers="uploadHeaders"
                    :file-list="files"
                    :on-change="changeFile"
                    :on-error="uploadError"
						        :on-success="uploadSuccess"
                    :show-file-list="false"
                    :multiple="false">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
                  </el-upload>
                </div>
              </li>
            </ul>
          </div>
          <div class="component-content screenSet upload-history-wrap">
            <p class="septal-line"></p>
            <p class="upload-record">上传历史记录：120</p>
            <el-table
              :data="searchData.tableData"
              class="upload-table"
              style="width: 100%">
              <el-table-column
                header-align="center"
                align="center"
                prop="fileName"
                label="文件名"
                width="180">
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="uploadTime"
                label="上传时间"
                width="180">
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="insertCount"
                label="新导入居民数">
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="updateCount"
                label="更新居民资料数">
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="status"
                label="处理状态">
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="address"
                label="关闭理由">
              </el-table-column>
            </el-table>
            <el-pagination
              class="pagination-style"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :total="searchData.totalCount"
              :current-page="1"
              :page-sizes="[10, 30, 50, 100]"
              :page-size="searchData.pageSize"
              layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
          </div>
        </el-tab-pane>
    </el-tabs>
    </div>

  </div>
</template>

<script>
  import BreadCrumb from "@/components/breadcrumb.vue";
  import EditInformation from '../mypatients-manage/components/edit-information'
  import * as commonUtil from "@/utils/utils";
  import {
    getQRCode,
    getUploadHistory,
    getLabelList,
    refreshCode,
    // getUploadHistory,
    savePatientInfo
  } from "@/utils/patients/patientsapi";
  import { getSaasDomain } from '@/utils/index';
  import QRCode from 'qrcode';

  export default {
    data() {
      return {
        curmbFirst: "居民管理",
        curmbSecond: "新增居民",
        activeName2: 'first',
        patientInfo: {},
        checkForm: false,
        patientId: '',
        searchData: {
          pageNo: 1,  // 第几页
          pageSize: 10,  // 每页条数
          tableData: [],
          totalCount: 0,
        },

        uploadUrl: `${getSaasDomain('web/patientManages/import')}`,
        uploadHeaders: {
          token: localStorage.getItem('token')
        },
        files: [],
        showChooseLabelModal: false,
        showReloadLabelModal: false,
        showDownloadQRModal: false,
        currentQRDownloadGroup: '',
        qrCodeInfo: {
          qrcodeUrl: '',
          beginTime: '',
          endTime: '',
          id: '',
          labelIds: '',
        },
        currentLabelList: [],
        labelNameList: [],
        choosedLabelList: [],
        qrDownloadGroups: [{
          value: '选项1',
          label: '黄金糕'
        }, {
          value: '选项2',
          label: '双皮奶'
        }, {
          value: '选项3',
          label: '蚵仔煎'
        }, {
          value: '选项4',
          label: '龙须面'
        }, {
          value: '选项5',
          label: '北京烤鸭'
        }]
      }
    },
    components: {
      BreadCrumb,
      EditInformation,
    },
    created() {
      this.goToGetQRCode({
        labelIds: '',
        id: '',
        first: true,
      });
      this.goToGetUploadHistory();
    },
    // 挂载到Dom完成时
    mounted() {
      // commonUtil.resizeHeight();
    },
    methods: {
      // 二维码录入
      goToGetQRCode(params){
        getQRCode(params).then(res => {
          if(res.code == '000000'){
            let data = res.data;
            this.qrCodeInfo = data;
            if(data.labelIds != ''){
              this.currentLabelList = data.labelIds.split(',');
            }
            this.calculateQRCode(data.qrcodeUrl);
          }else{
            this.$message({
              message: '获取二维码失败，请重新再试',
              type: 'warning'
            });
          }
        })
      },
      calculateQRCode(val){
        // 获取页面的canvas
        var msg= document.getElementById('msg')
        // 将获取到的数据（val）画到msg（canvas）上
        QRCode.toCanvas(msg, val, function (error) {
              console.log(error)
        })
      },
      handleChooseGroup() {
        this.showChooseLabelModal = true;
        this.goToGetGroupList();
      },
      handleRefreshCode() {
        let params = {
          labelIds: this.qrCodeInfo.labelIds,
          id: this.qrCodeInfo.id,
          first: false,
        }
        refreshCode(params).then(res => {
          if(res.code == '000000'){
            let data = res.data;
            this.qrCodeInfo = data;
            if(data.labelIds != ''){
              this.currentLabelList = data.labelIds.split(',');
            }
          }else{
            this.$message({
              message: '获取二维码失败，请重新再试',
              type: 'warning'
            });
          }
        })
      },
      handleQRDownloadModal() {
        this.showDownloadQRModal = true;
      },
      handleGoToDownloadQR() {
        alert('待接口OK')
      },
      handleAfterChooseLabel() {
        if(this.choosedLabelList.length < 1){
          this.$message({
            message: '请选择分组',
            type: 'warning'
          });
          return;
        }
        this.showChooseLabelModal = false;
        this.goToGetQRCode({
          labelIds: this.choosedLabelList.join(','),
          id: '',
          first: false,
        });
        this.choosedLabelList = [];
      },
      handleClearSelect() {
        this.choosedLabelList = [];
      },
      goToGetGroupList() {
        // 获取分组列表
        let params = {
          type: 1,
        };
        if(this.labelName){
          params.labelName = this.labelName;
        }
        getLabelList(params).then(data => {
          // console.log('获取分组列表>> ', data)
          if(data.data && data.data.labelNameList){
            this.labelNameList = data.data.labelNameList;
          }
        }).catch(err => {
          console.log('error: ', err)
        });
      },

      goToGetUploadHistory(){
        console.log('go get upload history>>>>>>')
        let params = {
          pageNo: this.searchData.pageNo,
          pageSize: this.searchData.pageSize,
        };
        getUploadHistory(params).then(res => {
          console.log('获取上传历史记录：', res);
          if(res.code == "000000"){
            if(res.data.importRecordsModelList.length > 0){
              this.searchData.tableData = res.data.importRecordsModelList;
              this.searchData.totalCount = res.data.count;
            }
          }else{
            // 获取失败
            this.$message({
              message: '接口返回失败，请重新再试',
              type: 'warning'
            });
          }
        })
      },
      handleTabClick(tab, event) {
        console.log(tab, event);
      },
      handleCurrentChange(val) {
        this.searchData.pageNo = val;
        this.goToGetUploadHistory();
      },
      handleSizeChange(val) {
        this.searchData.pageSize = val;
        this.goToGetUploadHistory();
      },
      handleDownloadDemo(){
        window.location.href = 'https://file.yunqueyi.com/File/template/居民导入模板.xlsx';
      },
      changeFile(file, fileList) {
        const name = file.name;
        const type = name.substring(name.lastIndexOf('.') + 1);

        if (type !== 'xls' && type !== 'xlsx') {
          this.$message({
            message: '上传文件只能是 xls、xlsx格式!',
            type: 'warning'
          });
          fileList.splice(0, 1);
          return false;
        }

        if (fileList.length > 1) {
          fileList.splice(0, 1);
        }

        this.files = [file];
      },
      uploadError(err, file, fileList){
        console.log('%c upload Error >>>>>>>>', 'color: red;')
      },
      uploadSuccess(response, file, fileList) {
        console.log('%c upload Success >>>>>>>>', 'color: red;')
        // this.loading = false;
        // this.visible = false;
        // this.tipShow = true;
        console.log('response: ', response);
        console.log('file: ', file);
        console.log('fileList: ', fileList)
        // console.log(response, file, fileList);
        const { code } = response;
        this.code = response.code;

        const codes = ['000000', '400002', '400004'];

        if (codes.indexOf(code) > -1) {
          this.error = response.data;
        } else {
          this.error = response.message;
        }
      },
      handleGoToLabelManage(){
        let routeUrl = this.$router.resolve({
          path: '/patients-manage/labels-manage/labels-list',
        });
        window.open(routeUrl.href, '_blank');
        this.showReloadLabelModal = true;
      },
      handleReloadLabel() {
        this.showReloadLabelModal = false;
        this.goToGetGroupList();
      },
      saveEdit() {
        this.checkForm = true;
      },
      addListenSave(val) {
        this.checkForm = false;
        if(val.status) {
          // this.patientInfo = val.patientInfoForm
          console.log('填写内容',val.patientInfoForm);
          savePatientInfo(val.patientInfoForm).then(data => {
            if(data.code == '000000'){
              this.$message.success('新增成功')
              setTimeout(() => {
                this.$refs.newForm.$refs.patientInfoForm.resetFields()
                // this.$router.go(0);//体验不好
              },500)
            }else {
              this.$message.error(data.message);
            }
          })
          //  调用保存接口
        }else {
          this.$message.error('请正确填写信息');
        }
      },
    }
  }

</script>

<style lang="less" scoped>
  
  @import "../../../style/patient-manager/new-patient/new-patient-wrap.less";
</style>

<style lang="less">
  @import "../../../style/patient-manager/new-patient/new-patient.less";
</style>

