<template>
  <div class="label-list-wrap label-detail-wrap">
    <bread-crumb
      :curmbFirst="curmbFirst"
      :curmbSecond="curmbSecond"
      :curmbThird="curmbThird"
      :jumPathThird="jumPathThird">
    </bread-crumb>
    <div class="component-content screenSet" id="screenSet">
      <div class="label-name">
        <p class="title">分组名称：</p>
        <p class="name">{{$route.query.labelName}}</p>
        <p class="modify" v-if="!isUngrouped" @click="handleChangeLabelName">修改</p>
        <el-button type="danger" plain size="small" class="delete-label" v-if="!isUngrouped" @click="goToDeleteLabel">删除分组</el-button>
      </div>
      <div class="label-member">
        <p class="title">分组成员：</p>
        <p class="member-number">{{searchData.totalRows}}人</p>
        <div class="right">
          <el-button type="primary" size="small" class="create-new-label" v-if="!isUngrouped" @click="addPatientsHandler">添加居民</el-button>
          <el-button type="default" size="small" class="create-new-label" v-if="!isUngrouped" :disabled="isBatchDeleteDisabled" @click="handleDeletePatients">批量移除</el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="searchData.tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :row-key="getRowKeys"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="55">
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="nickname"
          width="150">
        </el-table-column>
        <el-table-column
          label="性别"
          prop="sexStr"
          width="150">
        </el-table-column>
        <el-table-column
          label="年龄"
          prop="patientAge"
          width="150">
        </el-table-column>
        <el-table-column
          label="诊断"
          prop="patientTypeGroup"
          >
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
          >
          <template slot-scope="scope" v-if="!isUngrouped">
            <el-button
              class="remove-btn"
              @click="goToDeleteRow(scope.$index, searchData.tableData)"
              type="text"
              size="small">
              移除
            </el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <div class="table-empty" v-if="searchData.tableData && searchData.tableData.length < 1">
            <img class="empty-pic" src="../../../assets/image/no-content1.png">
            <p class="tips">当前分组暂无成员</p>
          </div>
        </div>
      </el-table>
      <el-pagination
         v-if="searchData.tableData && searchData.tableData.length > 0"
        class="pagination-style"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="searchData.totalRows"
        :current-page="searchData.pageNo"
        :page-sizes="[15, 30, 50, 100]"
        :page-size="searchData.pageSize"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <el-dialog
        title="修改名称"
        :visible.sync="showChangeLabelNameDialog"
        width="400px"
        center
        :show-close='false'
        :close-on-click-modal="false"
        >
        <el-form>
          <el-form-item :class="changeNameClass">
            <el-input
              type="textarea"
              v-model="ruleForm.newLabelName"
              placeholder="请填写分组名称，最多15个字符"
              maxlength="15"
              @input="handleNewNameInputChange"
              >
            </el-input>
            <div class="err-text">{{changeNameTips}}</div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelChangeName">取 消</el-button>
          <el-button type="primary" @click="confirmChangeName">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="删除分组"
        :visible.sync="centerDialogVisible"
        width="400px"
        center
        :show-close='false'
        :close-on-click-modal="false"
        >
        <div class="delete-tips">分组删除后，所有分组居民（共{{searchData.totalRows}}人）将不再属于此分组。</div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelDeleteLabel">取 消</el-button>
          <el-button type="primary" @click="confirmDeleteLabel">确认删除</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="移除居民"
        :visible.sync="showDeletePatientsDialog"
        width="400px"
        center
        :show-close='false'
        :close-on-click-modal="false"
        >
        <div class="delete-tips">移除后改居民将从分组中移除，若居民已没有任何分组，该居民将被自动分配至「未分组」</div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelDeletePatients">取 消</el-button>
          <el-button type="primary" @click="confirmDeletePatients">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <select-patient
      :isShowSelectPatient="isShowSelectPatient"
      :patientIdList="patientIdList"
      :oldPatientIdList="patientIdList"
      @closeSelectPatient="closeSelectPatient"
      :selectPatientType="selectPatientType"
      :sourceId="String(this.$route.query.labelId)"
      @sureSelectPatient="sureSelectPatient(arguments)"
    />
  </div>
</template>

<script>
  import BreadCrumb from "@/components/breadcrumb.vue";
  import * as commonUtil from "@/utils/utils";
  import {
    getLabelDetail,
    deleteCurrentLabel,
    changeLabelName,
    deleteCurrentPatients,
    saveLabelsForPatient,
  } from '@/utils/patients/patientsapi'
  import SelectPatient from './dialog/select-patitents';


  export default {
    data(){
      return {
        curmbFirst: "居民管理",
        curmbSecond: "分组管理",
        curmbThird: '分组详情',
        jumPathThird: '/patients-manage/labels-manage/labels-list',

        isChangeNameError: false,
        changeNameTips: '',
        showChangeLabelNameDialog: false,
        centerDialogVisible: false,
        showDeletePatientsDialog: false,
        isShowSelectPatient: false,
        patientIdList: [],
        sourceId: '',
        searchData: {
          pageNo: 1,  // 第几页
          pageSize: 15,  // 每页条数
          tableData: [],
          totalRows: 0,
        },
        ruleForm: {
          newLabelName: '', // 修改后的分组名
        },
        isSingleDelete: false,
        singleDeleteInfo: [],
        multipleSelection: [],
        selectPatientType: 2, //选择居民时需要的type类型
        getRowKeys(row) {
          // console.log('>>>> ', row)
          return row.id;
        },
      }
    },
    components: {
      BreadCrumb,
      SelectPatient,
    },
    computed: {
      changeNameClass() {
        return this.isChangeNameError == true ? 'special-error-tips' : ''
      },
      isUngrouped(){  // 是否未分组
        return this.$route.query.labelId == 0 ? true : false;
      },
      isBatchDeleteDisabled() {
        let selectList = this.multipleSelection;
        if(selectList.length < 1){
          return true;
        }
        return false;
      }
    },
    created() {
      this.getDetail();
    },
    // 挂载到Dom完成时
    mounted() {
      // commonUtil.resizeHeight();
    },
    methods: {
      getDetail() {
        let labelId = this.$route.query.labelId;
        // 获取分组详情
        let params = {
          pageNo: this.searchData.pageNo,
          pageSize: this.searchData.pageSize,
        };
        
        getLabelDetail(labelId, params).then(data => {
          // console.log('获取分组详情>> ', data)
          if(data.data){
            this.searchData = data.data;
            // this.patientIdList = data.data.patientIdList;
            let list = data.data.patientListsByLabelModels;
            if(list && list.length > 0){
              list = list.map(item => {
                if(!item.nickname){
                  item.nickname = '-';
                };
                if(!item.sexStr){
                  item.sexStr = '-';
                };
                if(item.patientAge || item.patientAge == 0){
                  // 直接显示
                }else{
                  item.patientAge = '-';
                };
                if(!item.patientTypeGroup){
                  item.patientTypeGroup = '-';
                }
                return item;
              })
              this.searchData.tableData = list;
            }else{
              this.searchData.tableData = [];
            }
          }
        }).catch(err => {
          console.log('error: ', err)
        });
      },

      handleSizeChange(val){
        console.log('handleSizeChange>>>')
        this.searchData.pageSize = val;
        this.getDetail();
      },
      handleCurrentChange(val){
        // 切换当前页
        this.searchData.pageNo = val;
        this.getDetail();
      },
      deleteLabel(){
        let labelId = this.$route.query.labelId;
        let params = {
          deleteList: [],
        };
        params.deleteList.push({
          labelId: labelId
        });
        deleteCurrentLabel(params).then(data => {
          // console.log('删除分组>> ', data)
          if(data.code == '000000'){
            this.centerDialogVisible = false;
            this.$router.replace({
              path: '/patients-manage/labels-manage/labels-list',
            })
          }else{
            this.$message({
              message: '删除分组失败，请重新再试',
              type: 'warning'
            });
          }
        }).catch(err => {
          console.log('error: ', err)
        });
      },
      goToDeleteLabel(){
        this.centerDialogVisible = true;
      },
      cancelDeleteLabel(){
        this.centerDialogVisible = false;
      },
      confirmDeleteLabel(){
        this.deleteLabel();
      },
      handleChangeLabelName(){
        this.showChangeLabelNameDialog = true;
        this.ruleForm.newLabelName = this.$route.query.labelName;
      },
      cancelChangeName(){
        this.isChangeNameError = false;
        this.ruleForm.newLabelName = '';
        this.showChangeLabelNameDialog = false;
      },
      handleNewNameInputChange(){
        this.isChangeNameError = false;
        this.changeNameTips = '';
      },
      // 更改分组名
      confirmChangeName() {
        let params = {
          labelId: this.$route.query.labelId,
          labelName: this.$route.query.labelName,
          newLabelName: this.ruleForm.newLabelName,
        };
        if(!params.newLabelName){
          this.isChangeNameError = true;
          this.changeNameTips = '请输入分组名称';
          return;
        }
        if( params.labelName == params.newLabelName ){
          this.isChangeNameError = true;
          this.changeNameTips = '该分组名称已被您使用，请重新输入';
          return;
        }
        changeLabelName(params).then(data => {
          if(data.code == '000000'){
            console.log('分组名修改成功');
            this.$message({
              message: '分组名修改成功',
              type: 'success'
            });
            this.cancelChangeName();
            this.$router.replace({
              path: '/patients-manage/labels-manage/labels-detail',
              query: {
                labelId: params.labelId,
                labelName: params.newLabelName,
              }
            })
          }else if(data.code == '202520'){
            this.isChangeNameError = true;
            this.changeNameTips = '该分组名称已被您使用，请重新输入';
          }else{
            this.$message({
              message: '请求接口失败，请重新再试',
              type: 'warning'
            });
          }
        }).catch(err => {
          console.log('error: ', err)
          this.$message({
            message: '请求接口失败，请重新再试',
            type: 'warning'
          });
        });
      },
      handleSelectionChange(val){
        console.log('handleSelectionChange>>>> ', val)
        this.multipleSelection = val;
      },
      goToDeleteRow(index, rows) {
        // console.log('before: ', this.multipleSelection)
        // this.$refs.multipleTable.toggleRowSelection(rows[index]);
        // console.log('after: ', this.multipleSelection)
        this.isSingleDelete = true;
        this.showDeletePatientsDialog = true;
        this.singleDeleteInfo = [{ patientId: rows[index].id }];
      },
      handleDeletePatients() {
        this.isSingleDelete = false;
        let selectList = this.multipleSelection;
        // console.log('list: ', selectList);
        let tempArr = [];
        for(let i=0; i<selectList.length; i++){
          tempArr.push({
            patientId: selectList[i].id
          })
        }
        this.multipleSelection = tempArr;
        this.showDeletePatientsDialog = true;
      },
      cancelDeletePatients() {
        this.showDeletePatientsDialog = false;
      },
      confirmDeletePatients() {
        let params = {
          labelId: this.$route.query.labelId,
          patientList: this.multipleSelection,
        };
        if(this.isSingleDelete == true){ // 点击单个移除时
          params.patientList = this.singleDeleteInfo;
        }
        deleteCurrentPatients(params).then(data => {
          if(data.code == '000000'){
            this.$message({
              message: '移除居民成功',
              type: 'success'
            });
            this.showDeletePatientsDialog = false;
            // 删除后去第一页
            this.handleCurrentChange(1);
          }else{
            this.$message({
              message: '请求接口失败，请重新再试',
              type: 'warning'
            });
          }
        }).catch(err => {
          console.log('error: ', err)
        });
      },
      addPatientsHandler() {
        this.isShowSelectPatient = true;
      },
      closeSelectPatient(val) {
        this.isShowSelectPatient = val;
      },
      sureSelectPatient() {
        let getArguments = arguments[0];
        const selectPatients = getArguments[1]; // 每次选中获取的人
        // const oldPatients = getArguments[2]; // 该分组已经存在的居民
        let labelId = this.$route.query.labelId;
        let patientLen = selectPatients.length;
        // let savePatientsList = selectPatients.concat(oldPatients);
        saveLabelsForPatient(labelId,{
          newLablelName: this.$route.query.labelName,
          oldLabelName: this.$route.query.labelName,
          saveLists: selectPatients,
          // token:
        }).then((data) => {
          if(data.code == '000000') {
            setTimeout(() => {
              this.$message.success(`已成功添加${patientLen}位居民`)
              this.isShowSelectPatient = getArguments[0];
              this.getDetail();
            },500)
          }else {
            this.$message.error(data.message)
          }
        })
      },
    }
  }
</script>

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

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