<template>
  <div class="select-patient-dialog">
    <el-dialog
      :title="selectPatientDialogTitle"
      :visible.sync="showSelectPatient"
      v-if="isShowSelectPatient"
      :before-close="clickClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="1100px"
      top="2%"
      center>
      <div class="finish-content">
        <el-form
          ref="searchData"
          :model="searchData"
          :inline="true"
          class="select-width"
          size="small">
          <div style="display: flex;justify-content: flex-end;margin-bottom: 15px">
            <el-button plain size="small" @click="goAddPatient">+ 新增居民</el-button>
          </div>
          <div style="display: flex;justify-content: space-between;">
            <div>
              <el-form-item prop="sex">
                <el-select
                  class="init-width"
                  v-model="searchData.sex"
                  placeholder="请选择性别"
                  clearable>
                  <el-option
                    v-for="(item,index) in sexOptions"
                    :key="index"
                    :label="item.value"
                    :value="item.no">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="ageRange">
                <el-select
                  v-model="searchData.ageRange"
                  multiple
                  collapse-tags
                  filterable
                  placeholder="请选择年龄段"
                  class="init-width2"
                  clearable>
                  <el-option
                    v-for="(item,index) in ageOptions"
                    :key="index"
                    :label="item.value"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="diseaseId">
                <!--<el-select
                  v-model="searchData.diseaseId"
                  multiple
                  collapse-tags
                  filterable
                  placeholder="请选择诊断"
                  class="set-width"
                  clearable>
                  <el-option
                    v-for="(item,index) in diseaseOptions"
                    :key="index"
                    :label="item.diseaseName"
                    :value="item.diseaseId">
                  </el-option>-->
                <!--</el-select>-->
                  <el-select
                    v-model="searchData.icdCodeList"
                    multiple
                    collapse-tags
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请选择或搜索诊断"
                    :remote-method="getDiseaseData"
                    :loading="loading"
                    class="set-width"
                  >
                    <el-option
                      v-for="item in icdOptions"
                      :key="item.icdCode"
                      :label="item.diseaseName"
                      :value="item.icdCode">
                    </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item prop="labelId">
                <el-select
                  v-model="searchData.labelId"
                  multiple
                  collapse-tags
                  filterable
                  class="set-width"
                  placeholder="请选择或搜索分组"
                  clearable>
                  <el-option
                    v-for="(item,index) in labelOptions"
                    :key="index"
                    :label="item.labelName"
                    :value="item.labelId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="fuPlanIdList" v-if="selectPatientType == 1">
                <el-select
                  v-model="searchData.fuPlanIdList"
                  multiple
                  collapse-tags
                  filterable
                  class="set-width"
                  placeholder="请选择履约计划"
                  clearable>
                  <el-option
                    v-for="(item,index) in fuPlanOptions"
                    :key="index"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="searchCondition">
                <el-input
                  v-model="searchData.searchCondition"
                  placeholder="请输入姓名,手机号,身份证"
                  clearable
                  class="set-width">
                  <!--<i slot="prefix" class="el-input__icon el-icon-search" @click="searchHandler" style="cursor: pointer"></i>-->
                </el-input>
              </el-form-item>
            </div>
            <div>
              <el-button type="primary" @click="searchHandler" size="small">查询</el-button>
              <el-button plain @click="resetData('searchData')" size="small">重置</el-button>
            </div>
          </div>
        </el-form>
        <el-table
          :data="patientsData"
          ref="multipleTable"
          center
          style="width: 100%;margin-top: 10px;"
          height="250"
          :row-key="getRowKeys"
          class="spe-table"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            align="center"
            :reserve-selection="true"
            :selectable="checkboxInit">
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="姓名"
            align="center">
          </el-table-column>
          <el-table-column
            prop="sexStr"
            label="性别"
            min-width="50"
            align="center">
          </el-table-column>
          <el-table-column
            prop="ageStr"
            label="年龄"
            min-width="50"
            align="center">
          </el-table-column>
          <el-table-column
            prop="mobilePhone"
            label="手机"
            align="center"
            min-width="130">
          </el-table-column>
          <el-table-column
            prop="idNoStr"
            label="身份证"
            align="center"
            min-width="130">
          </el-table-column>
          <el-table-column
            prop="showDiseaseNames"
            label="诊断"
            align="center"
            width="180"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            prop="showLabelName"
            label="分组"
            align="center"
            width="180"
            :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column
            v-if="selectPatientType == 1"
            prop="fuPlanName"
            label="履约计划"
            align="center"
            width="180"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span v-if="scope.row.fuPlanName">{{scope.row.fuPlanName}}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="space-between" align="middle" class="margin-top15">
          <!--<span>已选：{{newSelects.length}}人</span>-->
          <span></span>
          <el-pagination
            background
            v-if="patientsData.length"
            @size-change="handleSizeChangePre"
            @current-change="handleCurrentChangePre"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="paginationSet.pageNum"
            :page-sizes="[15,30,50,100]"
            :page-size="paginationSet.pageSize"
            :total="paginationSet.total">
          </el-pagination>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clickClose" size="small" plain>取 消</el-button>
        <el-button type="primary" size="small" @click="sureClick">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      class="reload-label-modal"
      :visible.sync="showReloadModal"
      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="handleReload">重新加载</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex'
  import { getConstants, getPatientInfoList, getDiseasesList, getLabelList, getIcdList } from '@/utils/patients/patientsapi'
  import { getPlanList } from '@/utils/followup/followapis'
  export default {
    components: {},
    name: "select-patient",
    data() {
      return {
        showSelectPatient: true,
        allSelects: [],
        // eachSelects: [],//仅仅是操作选择的总人员
//        totalSelect: [],// 当前所选的人
        srvPackageId: '',
        patientsData: [],
        searchData: {
          sex: null,
          ageRange: [],
          diseaseId: [],
          labelId: [],
          fuPlanIdList: [],
          searchCondition: '',
          icdCodeList: [],
        },
        paginationSet: {
          pageNum: 1,
          pageSize: 15,
          total: 0
        },
        sexOptions: [{
          no: '',
          value: '不限'
        }],
        ageOptions: [
          // {no: '', value: '年龄范围'}
        ],
        diseaseOptions: [
          // {diseaseId: '', diseaseName: '基础疾病'}
        ],
        labelOptions: [
          // {labelId: '', labelName: '分组'}
        ],
        fuPlanOptions: [],
        newSelects: [], //新选中的人
        oldPatientList: [],
        showReloadModal: false,
        loading: false,
        icdOptions: [],
        getRowKeys(row) {
          return row.patientId;
        },
        // 添加居民
      }
    },
    props: {
      isShowSelectPatient: Boolean, //是否显示model,
      patientIdList: Array,// 确定已经选过的居民
      oldPatientIdList: Array,// 确定已经选过的居民
      selectPatientType: Number, //获取居民列表所需字段，履约是1,分组是2，患教是3
      sourceId: {
        type: String,
        required: false,
        default: '',
      },
      selectPatientDialogTitle: {
        type: String,
        default: '添加居民'
      }
    },
    watch: {
      isShowSelectPatient(val){
        if(val){
          this.getPatientsList()
          //获取搜索诊断
          this.getDiseaseData();
          // 获取常量 性别、年龄
          getConstants({
            numList: 'P057,P006'
          }).then(res=>{
            this.sexOptions = [{
              no: '',
              value: '不限'
            }];
            this.sexOptions = this.sexOptions.concat(res.data.P006);//性别
            this.ageOptions = [
              // {no: '', value: '年龄范围'}
            ];
            this.ageOptions = this.ageOptions.concat(res.data.P057);//年龄段
          });

          // 获取所有疾病
          getDiseasesList().then(res=>{
            this.diseaseOptions = [
              // {diseaseId: '', diseaseName: '基础疾病'}
            ];
            this.diseaseOptions = this.diseaseOptions.concat(res.data);
          });

          // 获取所有分组
          getLabelList({type: 1}).then(res=>{
            this.labelOptions = [
              // {labelId: '', labelName: '分组'}
            ]
            this.labelOptions = this.labelOptions.concat(res.data.labelNameList);
          });

        //  获取履约计划列表
          getPlanList({
            pageNo: -1,
          }).then(res => {
            if(res.code == '000000') {
              this.fuPlanOptions = res.data.fPlanDtoList;
            }
          })
        }
      },
    },
    methods: {
      checkboxInit(row,index){
        if(row.disableNum == undefined) {
          return 1
        } else {
          return row.disableNum
        }
      },
      getDiseaseData(query) {
        // if (query !== '') {
          let params = {
            diseaseName: query ? query : '',
            pageSize: 200,
            pageNum: 1,
          };
          this.loading = true;
          getIcdList(params).then(data => {
            this.loading = false;
            if(data.code == "000000") {
              this.icdOptions = data.data;
            }
          }).catch((error) => {
            this.$message({
              message: error,
              type: 'error'
            });
          });
        // }else {
        //   this.icdOptions = [];
        // }
      },
      getPatientsList(){
        const data = {
          pageSize: this.paginationSet.pageSize,
          pageNo: this.paginationSet.pageNum,
          labelIdList:this.searchData.labelId,
          diseaseIdList: this.searchData.diseaseId,
          ageList: this.searchData.ageRange,
          sex: this.searchData.sex,
          searchCondition:this.searchData.searchCondition,
          srvPackageId:this.srvPackageId,
          addType: this.selectPatientType,   //履约是1,分组是2，患教是3
          fuPlanIdList: this.searchData.fuPlanIdList || [],
          sourceId: this.sourceId, //若是履约的话，传planId；若是分组的话，传labeledId;
          icdCodeList: this.searchData.icdCodeList
        }
        getPatientInfoList(data).then(res=>{
          if(res.data.patientList){
            this.patientsData = res.data.patientList //接口获取的当页居民
            this.getSex()
            this.paginationSet.total = res.data.totalRows
            // 设置所请求的当页人员是否成为选中状态
            // console.log('传入的已选居民',this.patientIdList)
            this.patientsData.forEach((item)=>{
              item.disableNum = 1;
              let diseaseNames = [];
              let groupNames = []
              //转化分组
              if(item.labelModels) {
                item.labelModels.forEach(item => {
                  groupNames.push(item.label)
                });
                item.showLabelName = groupNames.join('、');
              } else {
                item.showLabelName = '-';
              }

              //转化诊断
              if(item.patientTypeModels) {
                item.patientTypeModels.forEach(item => {
                  diseaseNames.push(item.diseaseName)

                })
                item.showDiseaseNames = diseaseNames.join('、');
              }else {
                item.showDiseaseNames = '-';
              }
              //针对履约项目
              if(this.patientIdList.length > 0){
                if(this.patientIdList.includes(item.patientId)){// 如果已经选过居民
                  this.$nextTick(()=>{
                    this.$refs.multipleTable.toggleRowSelection(item,true);
                  })
                }
              }
              if(this.oldPatientIdList!=undefined&&this.oldPatientIdList.length) {
                this.oldPatientList = [];
                this.patientsData.forEach((item)=>{
                  if(this.oldPatientIdList.includes(item.patientId)){// 如果已经选过居民
                    item.disableNum = 0;
                    this.oldPatientList.push(item);
                  } else {
                    item.disableNum = 1
                  }
                })
              }
              //针对分组详情
              // this.patientIdList = res.data.selectedPatientIdList;
              let selectedPatientIdList = res.data.selectedPatientIdList;
              if(selectedPatientIdList && selectedPatientIdList.length > 0){
                if(selectedPatientIdList.includes(item.patientId)){// 如果已经选过居民
                  this.$nextTick(()=>{
                    this.$refs.multipleTable.toggleRowSelection(item,true);
                  })
                }
              }
              if(selectedPatientIdList && selectedPatientIdList.length > 0) {
                this.patientsData.forEach((item)=>{
                  if(selectedPatientIdList.includes(item.patientId)){// 如果已经选过居民
                    item.disableNum = 0;
                    this.oldPatientList.push(item);
                  } else {
                    item.disableNum = 1
                  }
                })
              }
            })

            //  console.log(this.oldPatientIdList)
          }else{
            this.patientsData = []
          }
        })

      },
      getSex(){
        this.patientsData.forEach((item,index)=>{
          if(item.sex==1){
            this.patientsData[index].sexStr = '男'
          }else if(item.sex==2){
            this.patientsData[index].sexStr = '女'
          }else{
            this.patientsData[index].sexStr = '-'
          }

          if(!item.idNo) {
            this.patientsData[index].idNoStr = '-'
          }else {
            this.patientsData[index].idNoStr = item.idNo
          }
          if(item.age || item.age == 0) {
            this.patientsData[index].ageStr = item.age
          }else {
            this.patientsData[index].ageStr = '-'
          }
        })
      },
      // 对选中的居民进行去重
      removeDuplicates(list){
        return Array.from(new Set(list))
      },
      // 选择居民
      handleSelectionChange(val) {
        const _this = this;
        _this.newSelects = [];
        val.forEach(item => {
          if(item.disableNum == 1) {
            _this.newSelects.push(item)
          }
        })
      },
      // 切换分页
      handleCurrentChangePre(val) {
        this.paginationSet.pageNum = val
        this.getPatientsList()
        //控制切换页码的时候，滚动条滚到最上面
        this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
      },
      clickClose(){
//        this.searchData.searchCondition = ''
        this.searchData = {
          sex: null,
            ageRange: [],
            diseaseId: [],
            labelId: [],
            fuPlanIdList: [],
            searchCondition: '',
            icdCodeList: [],
        }
        this.$emit('closeSelectPatient',false)
      },
      sureClick(){
        if(this.newSelects.length) {
//          this.searchData.searchCondition = ''
          this.searchData = {
            sex: null,
            ageRange: [],
            diseaseId: [],
            labelId: [],
            fuPlanIdList: [],
            searchCondition: '',
            icdCodeList: [],
          }
          this.$emit('sureSelectPatient',false,this.newSelects,this.oldPatientList)
        } else {
          this.$message.warning('请先选择!')
        }

      },
      handleSizeChangePre(val) {
        this.paginationSet.pageSize = val;
        this.getPatientsList();
        this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
      },
      searchHandler() {
        this.paginationSet.pageNum = 1;
        this.getPatientsList();
        this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
      },
      resetData(formName) {
        this.$refs[formName].resetFields();
        this.getPatientsList();
        this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
      },
      goAddPatient() {
        // this.$router.push({
        //   path: '/patients-manage/new-manage/new-patient'
        // })
        let routeData = this.$router.resolve({ path: '/patients-manage/new-manage/new-patient' });
        window.open(routeData.href, '_blank');
        this.showReloadModal = true;
      },
      handleReload() {
        this.paginationSet.pageNum = 1;
        this.getPatientsList();
        this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
        this.showReloadModal = false;
      },
      ageDate(val){
        let ageObj;
        if(!val){
          ageObj = {
            ageBegin:'',
            ageEnd:''
          }
        }else if(val.indexOf('+') > -1){
          ageObj = {
            ageBegin: 84,
            ageEnd: 200
          }
        }else {
          let ageItem = val.split('-');
          ageObj = {
            ageBegin:ageItem[0],
            ageEnd:ageItem[1]
          }
        }
        return ageObj;
      }
    },
  }
</script>
<style lang="scss">
  .init-width{
    width: 100px !important;
    .el-input{
      width: 100px!important;
    }
  }
  .init-width2{
    width: 110px !important;
    .el-input{
      width: 110px!important;
    }
  }
  .set-width{
    width: 150px !important;
    .el-input{
      width: 150px!important;
    }
  }

</style>
<style lang="scss">
  @import '../../../../style/patients-style/element-reset.css';
  .select-patient-dialog {
    .el-dialog__wrapper {
      overflow: hidden;
      .el-dialog--center {
        /*height: 580px;*/
        .el-dialog__body{
          padding: 10px 25px 15px;
        }
        .el-table--scrollable-y,.el-table__body-wrapper {
          &::-webkit-scrollbar{
            width:5px;
          }
          &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
            border-radius: 10px;
            -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
            background: rgba(0,0,0,0.1);
          }
        }
        /*.el-dialog__body {
          max-height: 80%;
          overflow: hidden;
          .finish-content {
            height: 100%;
            .el-table {
              .el-table--scrollable-y .el-table__body-wrapper {
                height: 80%;
              }
            }

          }
        }*/
      }

    }
    .select-width .el-form-item{
      /*width: 130px;*/
    }
    .margin-top15{
      margin-top: 15px;
    }
    .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
      margin-bottom: 5px;
    }
    .el-select__tags-text{
      display: inline-block;
      max-width: 70px;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
    }
    .el-select .el-tag__close.el-icon-close{
      top: -5px;
    }

  }


</style>
