<template>
  <div class="select-patient-dialog">
    <el-dialog
      title="添加居民"
      :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 style="width: 100px;" prop="sex">
                <el-select
                  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 style="width: 100px;" prop="ageRange">
                <el-select
                  v-model="searchData.ageRange"
                  multiple
                  collapse-tags
                  filterable
                  placeholder="请选择年龄段"
                  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
                  style="width: 150px;"
                  placeholder="请选择诊断"
                  clearable>
                  <el-option
                    v-for="(item,index) in diseaseOptions"
                    :key="index"
                    :label="item.diseaseName"
                    :value="item.diseaseId">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="labelId">
                <el-select
                  v-model="searchData.labelId"
                  multiple
                  collapse-tags
                  filterable
                  style="width: 150px;"
                  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
                  style="width: 150px;"
                  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
                  style="width:150px;">
                  <!--<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"
          @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="age"
            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="idNo"
            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">
          </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>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex'
  import { getConstants, getPatientInfoList, getDiseasesList, getLabelList } 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: ''
        },
        paginationSet: {
          pageNum: 1,
          pageSize: 15,
          total: 0
        },
        sexOptions: [{
          no: '',
          value: '不限'
        }],
        ageOptions: [
          // {no: '', value: '年龄范围'}
        ],
        diseaseOptions: [
          // {diseaseId: '', diseaseName: '基础疾病'}
        ],
        labelOptions: [
          // {labelId: '', labelName: '分组'}
        ],
        fuPlanOptions: [],
        newSelects: [], //新选中的人
        oldPatientList: [],
        getRowKeys(row) {
          return row.patientId;
        },
      }
    },
    props: {
      isShowSelectPatient: Boolean, //是否显示model,
      patientIdList: Array,// 确定已经选过的居民
      oldPatientIdList: Array,// 确定已经选过的居民
      selectPatientType: Number, //获取居民列表所需字段，随访是1,分组是2，患教是3
    },
    watch: {
      isShowSelectPatient(val){
        if(val){
          this.getPatientsList()
          // 获取常量 性别、年龄
          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
        }
      },
      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 || [],
        }
        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.idNo) {
                item.idNo = '-';
              }
              //转化分组
              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.name)

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

            //  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 = '未知'
          }
        })
      },
      // 对选中的居民进行去重
      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()
      },
      clickClose(){
        this.$emit('closeSelectPatient',false)
      },
      sureClick(){
        if(this.newSelects.length) {
          this.$emit('sureSelectPatient',false,this.newSelects,this.oldPatientList)
        } else {
          this.$message.warning('请先选择!')
        }

      },
      handleSizeChangePre(val) {
        this.paginationSet.pageSize = val;
        this.getPatientsList();
      },
      searchHandler() {
        this.paginationSet.pageNum = 1;
        this.getPatientsList();
      },
      resetData(formName) {
        this.$refs[formName].resetFields();
        this.getPatientsList();
      },
      goAddPatient() {
        this.$router.push({
          path: '/patients-manage/new-manage/new-patient'
        })
      },
      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">
  @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: 86px;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
    }
    .el-select .el-tag__close.el-icon-close{
      top: -5px;
    }
  }


</style>
