<template>
  <div class="home">
    <el-row :gutter="20">
      <!-- 左侧计划列表区域 -->
      <el-col :span="6">
        <el-card style="width: 100%;">
          <!-- 搜索区域 -->
          <div class="card-title">
            <el-input v-model="form.name" placeholder="请输入计划名称" @keyup.enter="handleKeyUpEnter">
              <template #append>
                <el-button :icon="iconFlag ? ArrowDown : ArrowUp" @click="iconHandle" class="filter-button" />
              </template>
            </el-input>
            
            <!-- 高级搜索区域 -->
            <div class="serach-bottom" v-show="!iconFlag" style="width: 100%;">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="随访类型">
                    <el-select v-model="form.type" placeholder="请选择随访类型" style="width: 100%">
                      <el-option v-for="item in followType" :key="item.value" :label="item.title" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="随访方式">
                    <el-select v-model="form.way" placeholder="请选择随访方式" style="width: 100%">
                      <el-option v-for="item in followWay" :key="item.value" :label="item.title" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="状态">
                    <el-select v-model="form.state" placeholder="请选择状态" style="width: 100%">
                      <el-option label="未开始" value="0" />
                      <el-option label="进行中" value="1" />
                      <el-option label="终止" value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="时间范围">
                    <el-date-picker v-model="form.date1" type="daterange" range-separator="至" start-placeholder="开始时间"
                      end-placeholder="结束时间" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="search-buttons">
                <el-button type="primary" @click="handleSearch">查 询</el-button>
                <el-button @click="handleResult">重 置</el-button>
              </div>
            </div>
          </div>

          <!-- 添加计划按钮 -->
          <el-button type="primary" class="card-add-btn" @click="onAddItem">添加计划+ </el-button>

          <!-- 计划列表区域 -->
          <div class="card-content" ref="cardListRef" @scroll="doScroll">
            <el-card :class="index === borderIndex?'card-border':''"
              style="padding: 0; position: relative; margin-bottom: 5px;" v-for="(item,index) in planData"
              @click="handleItem(item,index)" :key="index">
              <div class="content-title">
                <el-icon class="icon-content" :size="20">
                  <Phone v-if="item.way === 1" />
                  <Message v-if="item.way === 2" />
                </el-icon>
                <div class="titleText">{{item.name}}</div>
              </div>
              <div class="content-center">
                时效:{{item.beginEffective.split(' ')[0]+'-'+item.endEffective.split(' ')[0]}}
              </div>
              <div>
                <el-button type="primary" plain>
                  {{item.cycle === 1 ? '每天' :'一次'}}
                </el-button>
              </div>
              <div class="content-bottom">
                创建人：{{item.createUser}}
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧计划详情区域 -->
      <el-col :span="18">
        <el-card style="width: 100%;">
          <!-- 详情标题区域 -->
          <div class="page-title">
            <div class="lf">{{planDetail.name}}</div>
            <el-button type="primary" link v-if="planDetail.state === 0">未开始</el-button>
            <el-button type="primary" link v-if="planDetail.state === 1">进行中</el-button>
            <el-button type="primary" link v-if="planDetail.state === 2">终止</el-button>
            <div class="btn">
              <el-button @click="handleEdit(planDetail)" v-show="planDetail.state === 2">编辑</el-button>
              <el-button @click="handleClose(planDetail.plId)" v-show="planDetail.state === 1">停用</el-button>
              <el-button @click="handleOpen(planDetail.plId)" v-show="planDetail.state === 2">开启</el-button>
              <el-button @click="handleCopy(planDetail)">复制</el-button>
              <el-button @click="handleDel(planDetail.plId)" v-show="planDetail.state === 2" type="danger">删除</el-button>
            </div>
          </div>
          
          <!-- 详情描述区域 -->
          <div class="page-content">
            {{planDetail.describes}}
          </div>
          <div class="page-describe">
            <span>创建人：{{planDetail.createUser}}</span>
            <span>创建时间：{{planDetail.createTime}}</span>
            <span>周期：{{planDetail.beginEffective}} ~ {{planDetail.endEffective}}</span>
            <span>患者数量：{{planDetail.total}}</span>
          </div>
          <div class="page-describe">
            外呼坐席：
            <span style="margin-right: 15px;" v-for="item in seatData">
              <span style="margin-right: 0px;" v-if="item.userName">{{item.userName}}</span>
              <span style="margin-right: 0px;" v-if="item.usercode">({{item.usercode}})</span>
            </span>
          </div>
          
          <!-- 详情选项卡区域 -->
          <div class="page-mian">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
              <el-tab-pane label="数据看板" name="first">
                <div class="tabList">
                  <data-board :planId="planId"></data-board>
                </div>
              </el-tab-pane>
              <el-tab-pane label="患者列表" name="second">
                <div class="tabList">
                  <patient-list v-if="activeName === 'second'" :planId="planId" :btnFlag="isdetilBtn"></patient-list>
                </div>
              </el-tab-pane>
              <el-tab-pane label="计划详情" name="third">
                <div class="tabList">
                  <project-details :planId="planId" ref="planDetails" :isdetil="1"></project-details>
                </div>
              </el-tab-pane>
              <el-tab-pane label="操作日志" name="fourth">
                <div class="tabList">
                  <operation-log :planId="planId"></operation-log>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 添加/编辑计划抽屉 -->
    <el-drawer
      v-model="drawer"
      v-if="drawer"
      :title="title"
      :direction="direction"
      :show-close="false"
      :close-on-click-modal="false"
      size="70%"
    >
      <project-details ref="projectAdd" :isdetil="2" @closeDrawerPlan="getCloseDrawer" :planId="editPlanId" :planState="planState"></project-details>
      <template #footer>
        <div class="box-btns" style="flex: auto">
          <el-button @click="cancelClick" style="margin-right: 30px;">取消</el-button>
          <el-button type="primary" @click="confirmClick" style="margin-right: 30px;">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="FollowUpPlan">
  import { onMounted, ref, onActivated } from 'vue';
  import { ArrowDown, ArrowUp } from '@element-plus/icons-vue';
  import moment from 'moment';
  import { getCurrentInstance } from 'vue';
  import { useRouter } from 'vue-router';
  
  // 组件导入
  import dataBoard from './cpns/dataBoard';
  import patientList from './cpns/patientFileList/patientFileList';
  import projectDetails from '../addFollowUpPlan/addFollowUpPlan';
  import operationLog from './cpns/operationLog';
  
  // API导入
  import { editPageData, getPageListData, getPageDetail, deletePageData } from '@/api/main/system/system';
  
  // 字典数据导入
  import { followType, followWay } from "@/utils/commonDic.js";
  
  // 获取全局实例
  const { proxy } = getCurrentInstance();
  
  // 路由相关
  const router = useRouter();
  
  // 基础数据定义
  const activeName = ref('first'); // 当前激活的选项卡
  const planParams = ref({        // 计划查询参数
    pageNum: 1,
    pageSize: 10
  });
  const form = ref({              // 搜索表单
    name: '',
    type: '',
    way: '',
    state: '',
    beginEffective: '',
    endEffective: ''
  });
  
  // 列表相关
  const borderIndex = ref(0);     // 当前选中的计划索引
  const isdetilBtn = ref(false);  // 是否显示详情按钮
  const iconFlag = ref(true);     // 是否显示高级搜索
  const contentData = ref([]);    // 当前页数据
  const planData = ref([]);       // 所有计划数据
  const planDetail = ref({});     // 当前选中的计划详情
  const planId = ref();           // 当前选中的计划ID
  const seatData = ref([]);       // 坐席数据
  const activatedFlag = ref(false); // 是否已激活
  const listTotal = ref(0);       // 总数据量
  const isLoading = ref(false);   // 是否正在加载
  
  // 抽屉相关
  const title = ref('添加计划');   // 抽屉标题
  const drawer = ref(false);      // 是否显示抽屉
  const direction = ref('rtl');   // 抽屉方向
  const editPlanId = ref('');     // 编辑的计划ID
  const planState = ref(0);       // 计划状态
  
  // 组件引用
  const projectAdd = ref(projectDetails);
  const planDetails = ref(projectDetails);
  const cardListRef = ref(null);
  
  /**
   * 取消抽屉
   */
  function cancelClick() {
    drawer.value = false;
    projectAdd.value.cleanForm();
  }
  
  /**
   * 确认抽屉
   */
  function confirmClick() {
    projectAdd.value.listSubmit();
  }
  
  /**
   * 关闭抽屉并刷新数据
   */
  function getCloseDrawer() {
    drawer.value = false;
    planId.value = null;
    planData.value = [];
    setTimeout(() => {
      isLoading.value = true;
      planParams.value.pageNum = 1;
      geFollowUpList();
    }, 100);
  }
  
  /**
   * 添加计划
   */
  function onAddItem() {
    editPlanId.value = 0;
    planState.value = 1;
    drawer.value = true;
  }
  
  /**
   * 选项卡点击事件
   */
  const handleClick = (tab, event) => {
    // 选项卡切换处理
  }
  
  /**
   * 切换高级搜索显示状态
   */
  function iconHandle() {
    iconFlag.value = !iconFlag.value;
  }
  
  /**
   * 组件激活时的处理
   */
  onActivated(() => {
    // borderIndex.value = 0;
    // planParams.value.pageNum = 1;
    // planId.value = '';
    // planData.value = [];
    // handleResult();
    // isLoading.value = true;
    // geFollowUpList();
  });
  
  /**
   * 组件挂载时的处理
   */
  onMounted(() => {
    borderIndex.value = 0;
    planParams.value.pageNum = 1;
    planId.value = '';
    activatedFlag.value = true;
    planData.value = [];
    isLoading.value = true;
    geFollowUpList();
  });
  
  /**
   * 回车搜索处理
   */
  function handleKeyUpEnter() {
    planParams.value.name = form.value.name;
    planParams.value.pageNum = 1;
    planData.value = [];
    isLoading.value = true;
    geFollowUpList();
  }
  
  /**
   * 搜索处理
   */
  function handleSearch() {
    iconFlag.value = !iconFlag.value;
    planParams.value.name = form.value.name;
    planParams.value.type = form.value.type;
    planParams.value.way = form.value.way;
    planParams.value.state = form.value.state;
    planParams.value.beginEffective = form.value.date1 && moment(form.value.date1[0]).format('YYYY-MM-DD HH:mm:ss');
    planParams.value.endEffective = form.value.date1 && moment(form.value.date1[1]).format('YYYY-MM-DD HH:mm:ss');
    planData.value = [];
    isLoading.value = true;
    geFollowUpList();
  }
  
  /**
   * 重置搜索条件
   */
  function handleResult() {
    // 重置表单数据
    form.value.name = '';
    form.value.type = '';
    form.value.way = '';
    form.value.state = '';
    form.value.date1 = '';
    
    // 重置查询参数
    planParams.value.name = '';
    planParams.value.type = '';
    planParams.value.way = '';
    planParams.value.state = '';
    planParams.value.beginEffective = '';
    planParams.value.endEffective = '';
    planParams.value.pageNum = 1;
  }
  
  /**
   * 获取随访计划列表
   */
  function geFollowUpList() {
    getPageListData("/SfPlan/sfPlan", planParams.value).then((res) => {
      // 如果没有选中计划，默认选中第一个
      if (!planId.value) {
        if (activatedFlag.value) {
          activatedFlag.value = false;
          planData.value = [];
          setTimeout(() => {
            planId.value = res.data[0].plId;
          }, 500);
        }
        planId.value = res.data[0].plId;
        planDetail.value = res.data[0];
        handleItem(planDetail.value, 0);
      }
      
      // 更新列表数据
      listTotal.value = res.total;
      contentData.value = res.data;
      planData.value = planData.value.concat(contentData.value);
      isLoading.value = false;
    });
  }
  
  /**
   * 获取计划坐席列表
   * @param {Number} plId - 计划ID
   */
  function getPlanSeatList(plId) {
    const params = { plId };
    seatData.value = [];
    getPageListData("/SfPlanSeats/sfplanseats", params).then((res) => {
      if (res.data.length > 0) {
        res.data.forEach(ele => {
          const obj = {};
          obj.userName = ele.userName ? ele.userName : ele.usercode;
          obj.usercode = ele.userName ? ele.usercode : '';
          seatData.value.push(obj);
        });
      }
    });
  }
  
  /**
   * 编辑计划
   * @param {Object} item - 计划对象
   */
  function handleEdit(item) {
    editPlanId.value = item.plId;
    planState.value = 0;
    drawer.value = true;
    title.value = '编辑计划';
  }
  
  /**
   * 复制计划
   * @param {Object} item - 计划对象
   */
  function handleCopy(item) {
    planState.value = 1;
    editPlanId.value = item.plId;
    drawer.value = true;
  }
  
  /**
   * 开启计划
   * @param {Number} planId - 计划ID
   */
  function handleOpen(planId) {
    editPageData('/SfPlan/sfPlan/modifyState/' + planId + '?state=1').then((data) => {
      proxy.$modal.msgSuccess('开启成功');
      const index = planData.value.findIndex(item => item.plId === planId);
      planData.value[index].state = 1;
      getPlanDetail(planId);
    });
  }
  
  /**
   * 停用计划
   * @param {Number} planId - 计划ID
   */
  function handleClose(planId) {
    editPageData('/SfPlan/sfPlan/modifyState/' + planId + '?state=2').then((data) => {
      proxy.$modal.msgSuccess('停用成功');
      const index = planData.value.findIndex(item => item.plId === planId);
      planData.value[index].state = 2;
      getPlanDetail(planId);
    });
  }
  
  /**
   * 获取计划详情
   * @param {Number} planId - 计划ID
   */
  function getPlanDetail(planId) {
    getPageDetail("/SfPlan/sfPlan/" + planId).then((res) => {
      planDetail.value = res.data;
      planDetails.value.getPlanDetail(planId);
      // 根据计划状态设置按钮显示
      isdetilBtn.value = planDetail.value.state !== 2;
    });
  }
  
  /**
   * 选择计划项
   * @param {Object} item - 计划对象
   * @param {Number} index - 索引
   */
  function handleItem(item, index) {
    borderIndex.value = index;
    planDetail.value = item;
    planId.value = item.plId;
    editPlanId.value = 0;
    planState.value = 0;
    
    getPlanSeatList(item.plId);
    // 根据计划状态设置按钮显示
    isdetilBtn.value = planDetail.value.state !== 2;
  }
  
  /**
   * 获取计划状态文本
   * @param {Number} value - 状态值
   * @returns {String} - 状态文本
   */
  function getPlanState(value) {
    let resultState = '';
    switch (Number(value)) {
      case 0:
        resultState = '未开始';
        break;
      case 1:
        resultState = '进行中';
        break;
      case 2:
        resultState = '终止';
        break;
    }
    return resultState;
  }
  
  /**
   * 滚动加载更多
   */
  function doScroll() {
    const scrollwrapper = cardListRef.value;
    if (scrollwrapper) {
      const { scrollTop, clientHeight, scrollHeight } = scrollwrapper; // 获取滚动数据
      // 判断是否滚动到底部
      if (scrollTop + clientHeight >= scrollHeight - 10 && !isLoading.value) {
        if (contentData.value.length > 9) {
          planParams.value.pageNum++;
          geFollowUpList();
        }
      }
    }
  }
  
  /**
   * 删除计划
   * @param {Number} plId - 计划ID
   */
  const handleDel = (plId) => {
    proxy.$modal.confirm('此操作将永久删除该计划, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      deletePageData('/SfPlan/sfPlan/' + plId).then((data) => {
        proxy.$modal.msgSuccess('删除成功');
        getCloseDrawer();
      });
    }).catch(() => {
      // 取消删除操作
    });
  };
</script>

<style scoped lang="scss">
  // 抽屉底部样式
  :deep(.el-drawer__footer) {
    padding: 0;
  }
  
  // 底部按钮区域
  .box-btns {
    border-top: 1px solid #d9d9d9;
    padding-top: 10px;
    height: 50px;
    text-align: right;
    width: 100%;
    background-color: #ffffff;
  }
  
  // 主容器样式
  .home {
    padding: 15px;

    // 卡片标题区域
    .card-title {
      display: flex;
      flex-direction: column;
      line-height: 30px;
      position: relative;

      // 筛选按钮
      .filter-button {
        border: none;
        background: transparent;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          color: #409EFF;
        }
      }

      // 高级搜索区域
      .serach-bottom {
        position: relative;
        padding: 12px;
        margin-top: 10px;
        background-color: #f8f9fa;
        border-radius: 4px;
        z-index: 11;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        
        .el-form-item {
          margin-bottom: 12px;
        }
      }
      
      // 搜索按钮区域
      .search-buttons {
        display: flex;
        justify-content: center;
        gap: 10px;
        margin-top: 5px;
        margin-bottom: 5px;
      }
    }

    // 添加计划按钮
    .card-add-btn {
      margin: 8px 0px;
      width: 100%;
    }

    // 计划列表区域
    .card-content {
      height: calc(100vh - 250px);
      margin-bottom: 15px;
      scrollbar-width: none; /* firefox */
      -ms-overflow-style: none; /* IE 10+ */
      overflow-x: hidden;
      overflow-y: auto;

      // 选中状态的卡片
      .card-border {
        border: 1px solid #409EFF;
        background: #409EFF;
        
        .content-title {
          display: flex;

          .icon-content {
            margin-right: 5px;
            color: #ffffff;
          }

          .titleText {
            font-size: 16px;
            font-weight: bold;
            line-height: 24px;
            color: #ffffff;
          }
        }

        .content-center {
          color: #ffffff;
          line-height: 40px;
          height: 40px;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          overflow: hidden;
          -webkit-box-orient: vertical;
          font-size: 14px;
        }

        .content-btn {
          display: flex;
        }

        .content-progress {
          margin: 8px 0px;
        }

        .content-bottom {
          display: flex;
          width: 100%;
          font-size: 14px;
          color: #ffffff;
          margin-top: 20px;

          .lf {
            width: 50%;
            display: inline-block;
            text-align: left;
          }

          .fr {
            width: 50%;
            display: inline-block;
            text-align: right;
          }
        }
      }

      // 普通卡片标题
      .content-title {
        display: flex;

        .icon-content {
          margin-right: 5px;
        }

        .titleText {
          font-size: 16px;
          font-weight: bold;
          line-height: 24px;
        }
      }

      // 普通卡片内容
      .content-center {
        line-height: 40px;
        height: 40px;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        overflow: hidden;
        -webkit-box-orient: vertical;
        color: #919191;
        font-size: 14px;
      }

      .content-btn {
        display: flex;
      }

      .content-progress {
        margin: 8px 0px;
      }

      // 普通卡片底部
      .content-bottom {
        display: flex;
        width: 100%;
        font-size: 14px;
        color: #919191;
        margin-top: 20px;

        .lf {
          width: 50%;
          display: inline-block;
          text-align: left;
        }

        .fr {
          width: 50%;
          display: inline-block;
          text-align: right;
        }
      }
    }

    // 详情页标题
    .page-title {
      display: flex;
      line-height: 30px;
      position: relative;

      .lf {
        font-size: 16px;
        display: inline-block;
        font-weight: bold;
        line-height: 38px;
        height: 38px;
        margin-right: 15px;
      }

      .btn {
        position: absolute;
        right: 30px;
        top: -3px;
      }
    }

    // 详情页内容
    .page-content {
      line-height: 20px;
      color: #919191;
      font-size: 14px;
    }

    // 详情页描述
    .page-describe {
      line-height: 38px;
      color: #919191;
      font-size: 14px;

      span {
        margin-right: 15px;
      }
    }

    // 详情页主体
    .page-mian {
      .tabList {
        height: calc(100vh - 360px);
        margin-bottom: 15px;
        scrollbar-width: none; /* firefox */
        -ms-overflow-style: none; /* IE 10+ */
        overflow-x: hidden;
        overflow-y: auto;
      }
    }
  }
</style>