<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" @click="handleDeletePatients">批量删除</el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="searchData.tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="nickname"
          width="120">
        </el-table-column>
        <el-table-column
          label="性别"
          prop="name"
          width="120">
        </el-table-column>
        <el-table-column
          label="年龄"
          prop="patientAge"
          width="120">
        </el-table-column>
        <el-table-column
          label="诊断"
          prop="dd"
          >
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
          >
          <template slot-scope="scope" v-if="!isUngrouped">
            <el-button
              class="remove-btn"
              @click.native.prevent="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="1"
        :page-sizes="[10, 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"
              >
            </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"
      @closeSelectPatient="closeSelectPatient"
      :selectPatientType="selectPatientType"
      @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: [],
        searchData: {
          pageNo: 1,  // 第几页
          pageSize: 10,  // 每页条数
          tableData: [],
          totalRows: 0,
        },
        ruleForm: {
          newLabelName: '', // 修改后的分组名
        },
        multipleSelection: [],
        selectPatientType: 2, //选择居民时需要的type类型
      }
    },
    components: {
      BreadCrumb,
      SelectPatient,
    },
    computed: {
      changeNameClass() {
        return this.isChangeNameError == true ? 'special-error-tips' : ''
      },
      isUngrouped(){  // 是否未分组
        return this.$route.query.labelId == 0 ? true : 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,
        };
        // commonUtil.openLoading(this);
        getLabelDetail(labelId, params).then(data => {
          // commonUtil.closeLoading(this);
          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){
              this.searchData.tableData = list;
            }else{
              this.searchData.tableData = [];
            }
          }
        }).catch(err => {
          console.log('error: ', err)
        });
      },
      handleSelectionChange(val){
        console.log('handleSelectionChange>>>> ', val)
        this.multipleSelection = val;
      },
      handleSizeChange(val){
        console.log('handleSizeChange>>>')
        this.searchData.pageSize = val;
        this.getDetail();
      },
      handleCurrentChange(val){
        console.log('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.$message({
            //   message: '删除分组成功',
            //   type: 'success'
            // });
            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;
      },
      // 更改分组名
      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{
            this.$message({
              message: '请求接口失败，请重新再试',
              type: 'warning'
            });
          }
        }).catch(err => {
          console.log('error: ', err)
          this.$message({
            message: '请求接口失败，请重新再试',
            type: 'warning'
          });
        });
      },
      goToDeleteRow(index, rows) {
        console.log('rows ', rows[index])
        this.showDeletePatientsDialog = true;
        this.multipleSelection.push({
          patientId: rows[index].id
        })
      },
      handleDeletePatients() {
        let selectList = this.multipleSelection;
        if(selectList.length < 1){
          this.$message({
            message: '请先勾选病人，再进行删除',
            type: 'error'
          });
          return;
        };
        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,
        };
        deleteCurrentPatients(params).then(data => {
          if(data.code == '000000'){
            this.$message({
              message: '移除居民成功',
              type: 'success'
            });
            this.showDeletePatientsDialog = false;
            this.getDetail();
          }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]; // 每次选中获取的人
        let labelId = this.$route.query.labelId;
        let patientLen = selectPatients.length;
        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>
