<template>
  <div class="resident-list">
    <div class="bread-crumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="(item, index) in residentCrumb" :key="index">
          <a v-if="item.href" :href="item.href">{{ item.name }}</a>
          <span v-else>{{ item.name }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="resident-content f-main-content screenSet">
      <p class="page-title">{{ planTitle }}</p>
      <div class="search-div">
        <div class="search-input">
          <el-form
            :model="searchData"
            ref="searchData"
            :inline="true"
            :label-width="labelWidth"
          >
            <el-form-item label="姓名：" prop="patientName">
              <el-input
                v-model:value="searchData.patientName"
                size="small"
                placeholder="请输入姓名"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号：" prop="mobile">
              <el-input
                v-model:value="searchData.mobile"
                size="small"
                placeholder="请输入手机号"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="分组：" prop="labelId">
              <el-select
                v-model:value="searchData.labelId"
                size="small"
                clearable
                :popper-append-to-body="false"
              >
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="item in groupList"
                  :key="item.labelId"
                  :label="item.labelName"
                  :value="item.labelId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="履约开始时间：" prop="startDate" size="small">
              <el-select
                v-model:value="searchData.startDate"
                size="small"
                clearable
                :popper-append-to-body="false"
              >
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="(item, index) in followStartTimeList"
                  :key="item + index"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-btn">
          <el-button
            class="button-green"
            type="primary"
            size="small"
            @click="searchResidentList"
            >查询</el-button
          >
          <el-button
            class="button-white"
            plain
            size="small"
            @click="resetSearchData('searchData')"
            >重置</el-button
          >
        </div>
      </div>
      <div class="resident-table table-content">
        <div class="btn-div">
          <el-radio-group v-model:value="status" size="small">
            <el-radio-button label="1"
              >未开始({{ residentList.notCount }})</el-radio-button
            >
            <el-radio-button label="2"
              >进行中({{ residentList.handCount }})</el-radio-button
            >
            <el-radio-button label="3"
              >已结束({{ residentList.yesCount }})</el-radio-button
            >
          </el-radio-group>
          <div class="btn-left">
            <el-button
              class="button-white"
              plain
              size="small"
              v-if="status == 3"
              @click="finishFollowup('all')"
              >恢复履约</el-button
            >
            <el-button
              class="button-white"
              plain
              size="small"
              v-else
              @click="finishFollowup('all')"
              >结束履约</el-button
            >
            <el-button
              class="button-green"
              type="primary"
              size="small"
              @click="selectPatientHandler"
              >添加居民</el-button
            >
          </div>
        </div>
        <el-table
          :data="residentList.fPlanPatientInfoDtoList"
          center
          @selection-change="handleSelectionChange"
          :row-key="getRowKeys"
          ref="tableData"
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column
            type="selection"
            align="center"
            :reserve-selection="true"
          >
          </el-table-column>
          <el-table-column prop="patientName" label="姓名" align="center">
            <template v-slot="scope">
              <el-button
                type="text"
                @click="
                  goPatientDetail(
                    scope.row.patientId,
                    scope.row.fuPlanPatientId
                  )
                "
                >{{ scope.row.patientName }}</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="sexName" label="性别" align="center">
          </el-table-column>
          <el-table-column prop="mobilePhone" label="手机" align="center">
          </el-table-column>
          <el-table-column
            width="160"
            prop="time"
            label="履约开始时间"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="labelName" label="分组" align="center">
          </el-table-column>
          <el-table-column
            width="190"
            fixed="right"
            label="操作"
            align="center"
          >
            <template v-slot="scope">
              <el-button
                class="btn-right-class"
                type="text"
                @click="changePlan(scope.row)"
                >变更计划</el-button
              >|
              <el-button
                class="btn-right-class"
                type="text"
                v-if="status == 3"
                @click="finishFollowup(scope.row)"
                >恢复履约</el-button
              >
              <el-button
                class="btn-right-class"
                type="text"
                v-else
                @click="finishFollowup(scope.row)"
                >结束履约</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            v-if="residentList.fPlanPatientInfoDtoList"
            @size-change="handleSizeChangePre"
            @current-change="handleCurrentChangePre"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="residentList.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="residentList.pageSize"
            :total="statusTotal"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <change-plan
      :showThisPage="showChangePlan"
      :planChangeData="planChangeData"
      @closeChangePlan="closeChangePlan"
    ></change-plan>
    <finish-followup
      :showThisPage="showFinishFollowup"
      :finishData="finishData"
      @closeFinishFollowup="closeFinishFollowup"
    ></finish-followup>
    <select-patient
      :isShowSelectPatient="isShowSelectPatient"
      :patientIdList="initialPatientIdList"
      :oldPatientIdList="initialPatientIdList"
      @closeSelectPatient="closeSelectPatient"
      @sureSelectPatient="sureSelectPatient(arguments)"
      :selectPatientType="selectPatientType"
    >
    </select-patient>
    <add-patient-time
      :showThisPage="showAddPatientTime"
      :addPatientData="addPatientData"
      @closeAddPatientTime="closeAddPatientTime"
    >
    </add-patient-time>
  </div>
</template>

<script>
//变更计划dialog
import ChangePlan from '@/views/followup/plan-manage/dialog/change-plan'
//结束履约dialog
import FinishFollowup from '@/views/followup/plan-manage/dialog/finish-followup'
//添加居民
// import SelectPatient from '@/views/followup/plan-manage/dialog/select-patient';
import SelectPatient from '@/views/patients/labels-manage/dialog/select-patitents'
//添加居民选择履约时间
import addPatientTime from '@/views/followup/plan-manage/dialog/add-patient-time'

import { mapState, mapActions } from 'vuex'
export default {
  name: 'residentList',
  components: {
    ChangePlan,
    FinishFollowup,
    SelectPatient,
    addPatientTime,
  },
  data() {
    return {
      labelWidth: '110px', //标题长度
      searchData: {
        labelId: '',
        startDate: '',
      }, //查询数据
      groupOption: [
        {
          // 分组选项
          value: '全部',
          label: '',
        },
      ],
      status: 1, //列表筛选条件
      showChangePlan: false, //是否展示变更计划
      planChangeData: {}, //变更计划数据
      showFinishFollowup: false, //是否展示结束履约
      finishData: {}, //结束数据
      isShowSelectPatient: false, //显示居民选择框
      hasSelectedList: [], //已选居民
      finishPatientList: [], //结束履约居民（多选）
      initialPatientIdList: [], //初始居民
      showAddPatientTime: false, //是否展示添加居民选择时间
      addPatientData: {}, //选择时间数据
      statusTotal: null, //每种状态的总数
      planTitle: '', //履约计划名称
      residentCrumb: [], //面包屑
      selectPatientType: 1,
      getRowKeys(row) {
        return row.patientId
      },
    }
  },
  created() {
    const vm = this
  },
  mounted() {
    this.getResidentList({
      planId: this.$route.query.planId,
      status: this.status,
    })
    this.getPlanStatusOption()
    this.getGroupList() //获取分组列表
    this.getFollowStartTimeList(this.$route.query.planId) // 获取履约时间列表
    let residentCrumbList = sessionStorage.getItem('residentCrumb')
    residentCrumbList = JSON.parse(residentCrumbList)
    if (
      residentCrumbList.length == 4 &&
      residentCrumbList[residentCrumbList.length - 1].name != '查看居民'
    ) {
      this.residentCrumb = residentCrumbList.slice(0, 2)
      this.residentCrumb.push({
        name: '查看居民',
        href: null,
      })
    } else if (
      residentCrumbList.length > 4 &&
      residentCrumbList[residentCrumbList.length - 1].name != '查看居民'
    ) {
      this.residentCrumb = residentCrumbList.slice(0, 3)
      this.residentCrumb.push({
        name: '查看居民',
        href: null,
      })
    } else {
      this.residentCrumb = residentCrumbList
    }
    this.setResidentCrumb(this.residentCrumb)
  },
  computed: {
    ...mapState('planManage', {
      residentList: (state) => state.residentList,
      groupList: (state) => state.groupList,
      planStatusOption: (state) => state.planStatusOption,
      followStartTimeList: (state) => state.followStartTimeList,
      selectResidentList: (state) => state.selectResidentList,
    }),
  },
  methods: {
    ...mapActions('planManage', [
      'getResidentList',
      'getGroupList',
      'getPlanStatusOption',
      'getFollowStartTimeList',
      'setResidentCrumb',
    ]),
    handleSizeChangePre(pageSize) {
      this.getResidentList({
        pageSize,
        ...this.searchData,
        status: this.status,
        planId: this.$route.query.planId,
      })
    },
    handleCurrentChangePre(pageNum) {
      this.getResidentList({
        pageNum,
        ...this.searchData,
        status: this.status,
        planId: this.$route.query.planId,
      })
    },
    goPatientDetail(patientId, fuPlanPatientId) {
      //居民详情页
      let residentCrumbs = []
      if (this.residentCrumb.length === 3) {
        residentCrumbs = [
          {
            name: '履约管理',
            href: null,
          },
          {
            name: '计划管理',
            href: `#/followup/plan-manage/plan-list`,
          },
          {
            name: '查看居民',
            href: `#/followup/plan-manage/resident-list?planId=${this.$route.query.planId}`,
          },
          {
            name: '居民详情',
            href: null,
          },
        ]
      } else if (this.residentCrumb.length === 4) {
        residentCrumbs = [
          {
            name: '履约管理',
            href: null,
          },
          {
            name: '计划管理',
            href: `#/followup/plan-manage/plan-list`,
          },
          {
            name: '计划详情',
            href: `#/followup/plan-manage/plan-detail??planId=${this.$route.query.planId}`,
          },
          {
            name: '查看居民',
            href: `#/followup/plan-manage/resident-list?planId=${this.$route.query.planId}`,
          },
          {
            name: '居民详情',
            href: null,
          },
        ]
      }

      this.setResidentCrumb(residentCrumbs)
      this.$router.push({
        path: '/followup/plan-manage/resident-detail',
        query: {
          patientId: patientId,
          planId: this.$route.query.planId,
          fuPlanPatientId: fuPlanPatientId,
        },
      })
    },
    searchResidentList() {
      //查询居民列表
      this.getResidentList({
        ...this.searchData,
        status: this.status,
        planId: this.$route.query.planId,
        pageNum: 1,
      })
    },
    resetSearchData(formName) {
      this.$refs[formName].resetFields()
      this.getResidentList({
        planId: this.$route.query.planId,
        status: this.status,
      })
    },
    changePlan(row) {
      this.planChangeData = {
        planPatientsId: row.fuPlanPatientId,
        // planId: this.$route.query.planId,
        patientId: row.patientId,
        yLabelList: row.labelIdList || [],
        // startDate:  row.time,
        status: this.status,
        planIdOld: this.$route.query.planId,
        patientName: row.patientName,
      }
      this.showChangePlan = true
    },
    closeChangePlan(isShow) {
      this.showChangePlan = isShow
    },
    finishFollowup(row) {
      if (row == 'all') {
        if (this.finishPatientList.length <= 0) {
          this.$message({
            message: '请选择居民！',
            type: 'warning',
          })
          return
        }
        let patientIds = []
        let patientNames = []
        let planPatientsIdList = []
        this.finishPatientList.forEach(function (item, index) {
          patientIds.push(item.patientId)
          patientNames.push(item.patientName)
          planPatientsIdList.push(item.fuPlanPatientId)
        })
        //          console.log(patientIds)
        if (patientNames.length > 5) {
          const le = patientNames.length
          patientNames = patientNames.slice(0, 5)
          patientNames = `${patientNames.join('、')}等${le}人`
        } else {
          patientNames = patientNames.join('、')
        }
        this.finishData = {
          changeCode: this.status,
          planId: this.$route.query.planId,
          patientName: patientNames,
          patientIdList: patientIds,
          title: this.status == 3 ? '恢复履约' : '结束履约',
          reasonName: this.status == 3 ? '恢复原因：' : '结束原因：',
          planPatientsIdList: planPatientsIdList,
        }
      } else {
        let patientIds = []
        let planPatientsIdList = []
        patientIds.push(row.patientId)
        planPatientsIdList.push(row.fuPlanPatientId)
        this.finishData = {
          changeCode: this.status,
          planId: this.$route.query.planId,
          patientName: row.patientName,
          patientIdList: patientIds,
          title: this.status == 3 ? '恢复履约' : '结束履约',
          reasonName: this.status == 3 ? '恢复原因：' : '结束原因：',
          planPatientsIdList: planPatientsIdList,
        }
      }
      this.showFinishFollowup = true
    },
    closeFinishFollowup(isShow) {
      this.showFinishFollowup = isShow
    },
    selectPatientHandler() {
      this.isShowSelectPatient = true
    },
    closeSelectPatient(val) {
      this.isShowSelectPatient = val
    },
    closeAddPatientTime(isShow) {
      this.showAddPatientTime = isShow
    },
    sureSelectPatient() {
      let getArguments = arguments[0]
      this.isShowSelectPatient = getArguments[0]
      const selectPatients = getArguments[1] // 每次选中获取的人

      let patientIds = []
      let patientNames = []

      selectPatients.forEach((item) => {
        patientIds.push(item.patientId)
        patientNames.push(item.nickname)
      })
      // 将选择的patientIds存入Store中

      if (patientNames.length > 5) {
        const le = patientNames.length
        patientNames = patientNames.slice(0, 5)
        patientNames = `${patientNames.join('、')}等${le}人`
      } else {
        patientNames = patientNames.join('、')
      }
      this.addPatientData = {
        id: this.$route.query.planId,
        addPatients: true,
        patientIdList: patientIds,
        patientNames: patientNames,
        status: this.status,
      }
      this.showAddPatientTime = true
    },
    handleSelectionChange(val) {
      //        console.log('已选居民',val)
      this.finishPatientList = val
    },
  },
  watch: {
    status(val) {
      this.getResidentList({
        status: val,
        ...this.searchData,
        planId: this.$route.query.planId,
      })
      this.$refs.tableData.clearSelection()
    },
    residentList(val) {
      if (this.status == 1) {
        this.statusTotal = val.notCount
      } else if (this.status == 2) {
        this.statusTotal = val.handCount
      } else if (this.status == 3) {
        this.statusTotal = val.yesCount
      }
    },
    selectResidentList(val) {
      const _this = this
      if (val) {
        val.forEach(function (item, index) {
          _this.initialPatientIdList.push(item.patientId)
        })
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (from.name === 'planList') {
        vm.curmbSecond = '计划管理'
        vm.jumPathThird = '/followUp/plan-manage'
      } else if (from.name === 'planDetail') {
        vm.curmbSecond = '计划详情'
        vm.jumPathThird = `/followUp/plan-manage/plan-detail?planId=${vm.$route.query.planId}`
      }
      vm.planTitle = vm.$route.query.planName
    })
  },
}
</script>

<style lang="scss" scoped>
@import '../../../style/followup/followup-common';
@import '../../../style/followup/element-reset.css';
.bread-crumb {
  position: fixed;
  left: 255px;
  top: 64px;
  width: 100%;
  background: #fff;
  height: 61px;
  padding: 20px 20px 30px;
  z-index: 99;
  border-top: 3px solid #f0f2f5;
  .el-breadcrumb__inner {
    font-size: 14px;
  }
  a:hover {
    color: #449284;
  }
}
.btn-left {
  float: right;
}
</style>
