<template>
  <lay-container fluid="true" class="organization-box">
    <div style="display: flex">
      <div :style="{ width: isFold ? `0px` : `230px` }" class="left-tree">
        <div v-if="!isFold">科室列表</div>
        <lay-tree v-show="!isFold" style="margin-top: 10px" :data="data" v-model:selectedKey="group_id"
          :showLine="false" @node-click="handleClick">
          <template #title="{ data }">
            <span :class="group_id == data.id ? 'isChecked' : ''">
              {{ data.name }}
            </span>
          </template>
        </lay-tree>
        <div class="isFold" @click="isFold = !isFold">
          &nbsp;<lay-icon v-if="!isFold" class="layui-icon-left"></lay-icon>
          <lay-icon v-else class="layui-icon-right"></lay-icon>
        </div>
      </div>
      <div style="flex: 1; padding: 10px; overflow: auto">
        <!-- table -->
        <lay-card>
          <lay-form>
            <lay-row>
              <lay-col :md="5">
                <lay-form-item label="年" label-width="80px">
                  <lay-date-picker type="year" v-model="year" placeholder="年" allow-clear></lay-date-picker>
                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label="季度" label-width="80px">
                  <lay-select v-model="quarter" placeholder="请选择">
                    <lay-select-option :value="1" label="第一季度"></lay-select-option>
                    <lay-select-option :value="2" label="第二季度"></lay-select-option>
                    <lay-select-option :value="3" label="第三季度"></lay-select-option>
                    <lay-select-option :value="4" label="第四季度"></lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col :md="6">
                <lay-form-item label="考评对象" label-width="80px">
                  <lay-select v-model="userId" :show-search="true" placeholder="请选择" :allowClear="true">
                    <lay-select-option v-for="item in dataSerSource" :value="item.id" :label="item.nickname+'('+item.code+')'"></lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label-width="20">
                  <lay-button style="margin-left: 20px" type="primary" size="sm" @click="toSearch">
                    查询
                  </lay-button>
                  <lay-button size="sm" @click="toReset"> 重置</lay-button>
                </lay-form-item>
              </lay-col>
            </lay-row>
          </lay-form>
        </lay-card>
        <lay-tab v-model="tab_id" @change="openTab">
          <lay-tab-item v-for="item in tabList" :title="item.title" :id="item.id"></lay-tab-item>
        </lay-tab>
        <lay-table :page="page" height="600px" :columns="columns" :loading="loading" :data-source="dataSource"
          @change="pageChange">
          <template v-slot:scoringrecord_status="{ row }">
            <lay-tag v-if="row.scoringrecord_status == 1" type="primary" size="sm">已自评</lay-tag>
            <lay-tag v-if="row.scoringrecord_status == 2" size="sm">未自评</lay-tag>
            <lay-tag v-if="row.scoringrecord_status == 3" type="warm" size="sm">科室已评</lay-tag>
            <lay-tag v-if="row.scoringrecord_status == 4" type="danger" size="sm">医院已评</lay-tag>
          </template>
          <template v-slot:nickname="{ row }">
            <div style="color: #00A394;cursor: pointer" @click="openUserListShow(row)">{{ row.nickname }}</div>
          </template>
          <template v-slot:operator="{ row }">
            <lay-space>
              <span style="color: #00A394;cursor: pointer"
                v-if="row.scoringrecord_status == 3 && userStore.userInfo.level == 3"
                @click="getInfo(row, 3)">医院评分</span>
              <span style="color: #00A394;cursor: pointer" v-if="row.scoringrecord_status == 1"
                @click="getInfo(row, 2)">科室评分</span>
              <span style="color: #00A394;cursor: pointer" v-if="row.scoringrecord_status != 2"
                @click="getInfo(row, 1)">考评详情</span>
              <span style="color: #999999;cursor: not-allowed" v-if="row.scoringrecord_status == 2">未自评</span>
            </lay-space>
          </template>
        </lay-table>
      </div>
    </div>
    <lay-layer v-model="infoShow" title="自评详情" :type="4" :shade="true" :area="['950px', '100%']"
      :btn="addIsInfo != 1 ? addButton : ''"> 
      <lay-container fluid="true" style="padding: 20px">
        <lay-table :default-expand-all="true" ref="tableRef6" children-column-name="children" :columns="columns6"
          :data-source="dataSource6">
          <template v-slot:base_score="{ data }">
            <div v-if="data.pid == 0">题目分：{{ data.base_score }}</div>
            <div v-if="data.pid != 0">{{ data.base_score }}</div>
          </template>
          <template v-slot:content_score="{ row, column, rowIndex }">
            <div v-if="row.pid == 0">已评分：{{ row.avg_score ? row.avg_score : 0 }}</div>
            <lay-input-number @change="inputChange(row)" v-if="row.pid != 0" :disabled="true" :min="0"
              :max="row.base_score" v-model="row.content_score" position="right"></lay-input-number>
          </template>
          <template v-slot:department_score="{ row, rowIndex }">
            <div v-if="row.pid == 0">已评分：{{ row.department_score ? row.department_score : 0 }}</div>
            <lay-input-number :disabled="addIsInfo==1" @change="inputKsChange(row)" v-if="row.pid != 0" :min="0" :max="row.base_score" v-model="row.department_score"
              position="right"></lay-input-number>
          </template>
        </lay-table>
      </lay-container>
    </lay-layer>
    <lay-layer v-model="userShow" title="季度自评列表" :shade="true" :area="['90%', '90%']">
      <lay-container fluid="true" style="padding: 20px">
        <lay-row :space="10">
          <lay-col :md="24">
            <lay-card>
              <lay-form style="margin-top: 20px">
                <lay-row>
                  <lay-col :md="5">
                    <lay-form-item label="年度：" label-width="50">
                      <lay-date-picker type="year" v-model="searchAccountUser" placeholder="请选择"
                        allow-clear></lay-date-picker>
                    </lay-form-item>
                  </lay-col>
                  <lay-col :md="4">
                    <lay-form-item label-width="0">
                      <lay-button type="primary" size="sm" @click="toUserSearch">查询</lay-button>
                      <lay-button size="sm" @click="toReset">重置</lay-button>
                    </lay-form-item>
                  </lay-col>
                </lay-row>
              </lay-form>
            </lay-card>
          </lay-col>
          <lay-col :md="24">
            <lay-tab v-model="userTabId" @change="openUserTab">
              <lay-tab-item v-for="item in tabList" :title="item.title" :id="item.id"></lay-tab-item>
            </lay-tab>
            <lay-table height="400px" :default-expand-all="true" :columns="userColumns"
                  :data-source="userDataSource">
                  <template v-slot:scoringrecord_status="{ row }">
                    <lay-tag v-if="row.scoringrecord_status == 1" type="primary" size="sm">已自评</lay-tag>
                    <lay-tag v-if="row.scoringrecord_status == 2" size="sm">未自评</lay-tag>
                    <lay-tag v-if="row.scoringrecord_status == 3" type="warm" size="sm">科室已评</lay-tag>
                    <lay-tag v-if="row.scoringrecord_status == 4" type="danger" size="sm">医院已评</lay-tag>
                  </template>
                  <template v-slot:operator="{ row }">
                    <span v-if="row.if == 2" style="color: #00A394;cursor: pointer"
                      @click="getMonthlyInfo(row, 1)">考评详情</span>
                    <span style="color: #999999;cursor: not-allowed" v-if="row.if == 1">未自评</span>
                  </template>
                </lay-table>
          </lay-col>
        </lay-row>
      </lay-container>
    </lay-layer>
  </lay-container>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { layer } from '@layui/layui-vue'
import {
  getUserGroupNew,
  getGroupQuarter,
  getQuarterUserList,
  getQuarterListFind,
  getQuarterListUpdate,
  getQuarterlyFindData
} from "@/api/module/home";
import dayjs from "dayjs";
import { useUserStore } from '@/store/user';
import { useRoute } from 'vue-router'
const route = useRoute()
const userStore = useUserStore()
const userId = ref();
onMounted(() => {
  if(route.params.id){
    console.log(route.params.id);
    
    userId.value = parseInt(route.params.id);
  }
  getLeftList();
})
const userShow = ref(false);
const userColumns = ref([
  { title: '季度', width: '80px', key: 'quarter', align: 'center' },
  { title: '考评对象', width: '100px', key: 'user', align: 'center' },
  { title: '参评时间', width: '100px', key: 'createtime', align: 'center', customSlot: ({row})=>{
    return row.createtime==''||row.createtime==null?'未参评':row.createtime;
  } },
  { title: '自评总分', width: '100px', key: 'self_score', align: 'center', customSlot: ({row})=>{
    return row.self_score==''||row.self_score==0?'未评分':row.self_score;
  } },
  { title: '科室评分', width: '100px', key: 'department_score', align: 'center', customSlot: ({row})=>{
    return row.department_score==''||row.department_score==0?'未评分':row.department_score;
  } },
  // { title: '医院评分', width: '100px', key: 'hospital_score', align: 'center' },
  { title: '状态', width: '100px', key: 'scoringrecord_status', customSlot: 'scoringrecord_status', align: 'center' },
  { title: '操作', width: '100px', key: 'operator', customSlot: 'operator', align: 'center' },
])
const userDataSource = ref([]);
const userTabId = ref(0);
const userInfo = ref({});
const searchAccountUser = ref(dayjs().year());
const openUserListShow = (row) => {
  userInfo.value = row;
  userShow.value = true;
  userDataSource.value = [];
  getUserListInfo();
}
const inputChange = (row) => {
  //计算出dataSource6里分数在children下所有的已评总分 
  let total = 0;
  const index = dataSource6.value.findIndex(item => item.id === row.pid);
  dataSource6.value[index].children.forEach(item => {
    total += parseInt(item.content_score);
  });
  //找到row的index
  dataSource6.value[index].avg_score = total;
  dataSource6.value[index].content_score = total;
}
//科室评分总分
const inputKsChange = (row) => {
  //计算出dataSource6里分数在children下所有的已评总分 
  let total = 0;
  const index = dataSource6.value.findIndex(item => item.id === row.pid);
  dataSource6.value[index].children.forEach(item => {
    total += parseInt(item.department_score);
  });
  dataSource6.value[index].department_score = total;
}
//科室评分总分
const inputListKsShow = () => {
  //计算出dataSource6里分数在children下所有的已评总分 
  dataSource6.value.forEach((item, index) => {
    let total = 0;
    item.children.forEach(item2 => {
      total += parseInt(item2.department_score);
    });
    dataSource6.value[index].department_score = total;
  });
}
//自评列表总分
const inputListZpShow = () => {
  //计算出dataSource6里分数在children下所有的已评总分 

  dataSource6.value.forEach((item, index) => {
    let total = 0;
    item.children.forEach(item2 => {
      total += parseInt(item2.content_score);
    });
    dataSource6.value[index].avg_score = total;
    dataSource6.value[index].content_score = total;
  });
}
const getUserListInfo = () => {
  getQuarterlyFindData({
    'user_id': userInfo.value.id,
    'evaluation_id': userTabId.value,
    'time': searchAccountUser.value
  }).then((res) => {
    console.log(res)
    if (res.code == 1) {
      userDataSource.value = res.data;
    } else {
      userDataSource.value = [];
    }
  })
}
const openUserTab = (d) => {
  console.log(d)
  userTabId.value = d;
  userDataSource.value = [];
  getUserListInfo();
}
const getMonthlyInfo = (item, type) => {
  addIsInfo.value = type;
  infoShow.value = true;
  console.log(item);
  item.time = item.quarter;
  getInfoMode(item);
}
const toUserSearch = () => {
  getUserListInfo();
}
const openTab = (d) => {
  console.log(d)
  tab_id.value = d;
  dataSource.value = [];
  page.current = 1;
  getList();
}
const page = reactive({ current: 1, limit: 10, total: 1 })
const pageChange = (d) => {
  console.log(d);
  page.current = d.current;
  page.limit = d.limit;
  getList();
}
const addIsInfo = ref(1);
const infoShow = ref(false);
const year = ref(dayjs().year());
const quarter = ref(1);


const yearmonth = ref();
const getList = () => {
  getQuarterUserList({
    'user_id': userId.value,
    'group_id': group_id.value,
    'time': yearmonth.value,
    'evaluation_schedule_id': tab_id.value,
    page: page.current,
    size: page.limit
  }).then((res) => {
    console.log(res)
    if (res.code == 1) {
      dataSource.value = res.data.result;
      page.total = res.data.count;
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}
const dataSerSource = ref([]);
const getSserList = () => {
  getQuarterUserList({
    'group_id': group_id.value,
    'time': yearmonth.value,
    'evaluation_schedule_id': tab_id.value,
    page: 1,
    size: 999
  }).then((res) => {
    console.log(res)
    if (res.code == 1) {
      dataSerSource.value = res.data.result;
      page.total = res.data.count;
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}

const thisInfo = ref();
const getInfo = (row, type) => {
  infoShow.value = true;
  addIsInfo.value = type;
  console.log(row);
  thisInfo.value = row;
  getInfoMode(row);
  // if (row.scoringrecord_status == 4 && userStore.userInfo.level != 3) {
  //   columns6.push({
  //     title: "医院评分",
  //     width: "100px",
  //     align: 'center',
  //     customSlot: 'yyinput',
  //     key: "yyinput"
  //   });
  // }

}

const getInfoMode = (row) => {
  getQuarterListFind({
    evaluation_schedule_id: tab_id.value,
    month: row.time,
    user_id: row.id
  }).then((res) => {
    console.log(res)
    if (res.code == 1) {
      dataSource6.value = res.data;
      inputListZpShow();
      inputListKsShow();
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}
const tabList = ref([]);
const tab_id = ref(0);
const getTabList = () => {
  getGroupQuarter({ 'group_id': group_id.value }).then((res) => {
    console.log(res)
    if (res.code == 1) {
      tabList.value = res.data;
      tab_id.value = res.data[0].id;
      userTabId.value = res.data[0].id;
      getList();
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}
const group_id = ref(1);
const getLeftList = () => {
  getUserGroupNew({}).then((res) => {
    console.log(res)
    if (res.code == 1) {
      data.value = res.data;
      group_id.value = res.data[0].id;
      getTabList();
      getSserList();
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}
const data = ref([])
const isFold = ref(false)
const searchQuery = ref({
  year: '',
  evaluateTarget: '',
  status: ''
})

function toReset() {
  searchQuery.value = {
    year: '',
    evaluateTarget: '',
    status: ''
  }
  userId.value = '';
  getList();
  getSserList();
}

function handleClick(node: any) {
  // selectedNode.value = JSON.parse(JSON.stringify(node))
  page.current = 1;
  group_id.value = node.id;
  getList();
  getSserList();
  // change(page)
}

function toSearch() {
  page.current = 1;
  yearmonth.value = year.value + '-' + quarter.value;
  getList();
}

const loading = ref(false)
const selectedKeys = ref()
const columns = ref([
  { title: '选项', width: '55px', type: 'checkbox', align: 'center' },
  { title: '序号', width: '60px', key: 'id', align: 'center' },
  { title: '季度', width: '80px', key: 'time', align: 'center' },
  { title: '考评对象', width: '100px', key: 'nickname', customSlot: 'nickname', align: 'center' },
  { title: '工号', width: '100px', key: 'code', align: 'center' },
  { title: '部门', width: '120px', key: 'group_name', align: 'center' },
  // { title: '医院评分', width: '100px', key: 'hospital_score_scoringrecord', align: 'center' },
  { title: '科室评分', width: '100px', key: 'department_score_scoringrecord', align: 'center', customSlot: ({row})=>{
    return row.department_score_scoringrecord==''||row.department_score_scoringrecord==0?'未评分':row.department_score_scoringrecord;
  } },
  { title: '自评总分', width: '100px', key: 'user_scoringrecord', align: 'center', customSlot: ({row})=>{
    return row.user_scoringrecord==''||row.user_scoringrecord==0?'未评分':row.user_scoringrecord;
  } },
  { title: '自评状态', width: '100px', key: 'scoringrecord_status', customSlot: 'scoringrecord_status', align: 'center' },
  {
    title: '操作',
    width: '180px',
    customSlot: 'operator',
    key: 'operator',
    fixed: 'right', align: 'center'
  }
])
const dataSource = ref()
const addButton = ref([
  {
    text: "确认",
    callback: async () => {
      var json = JSON.stringify(dataSource6.value);
      var res = await getQuarterListUpdate({
        'term': thisInfo.value.time,
        'json': json,
        'user_id': thisInfo.value.id,
        evaluation_schedule_id: tab_id.value
      });
      console.log(res)
      if (res.code == 1) {
        layer.msg('提交成功！', { icon: 1 })
        thisInfo.value = {};
        infoShow.value = false;
        getList();
      } else {
        layer.msg(res.msg, { icon: 2 })
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      infoShow.value = false;
    }
  }
])
const columns6 = [
  {
    title: "考评项目",
    width: "300px",
    key: "project_name"
  },
  {
    title: "分值",
    width: "80px",
    align: 'center',
    key: "base_score",
    customSlot: 'base_score',
    totalRow: true
  },
  {
    title: "自评分",
    width: "100px",
    align: 'center',
    customSlot: 'content_score',
    key: "content_score",
    totalRow: true
  },
  {
    title: "科室评分",
    width: "100px",
    align: 'center',
    customSlot: 'department_score',
    key: "department_score",
    totalRow: true
  }
]
// 根据用户级别动态添加医院评分列
// if (userStore.userInfo.level == 3) {
//   columns6.push({
//     title: "医院评分",
//     width: "100px",
//     align: 'center',
//     customSlot: 'yyinput',
//     key: "yyinput"
//   });
// }
const dataSource6 = ref([])
</script>

<style>
.layui-table-header .layui-table-cell {
  background-color: #ECF8FA !important;
}

.organization-box {
  width: calc(100vw - 240px);
  height: calc(100vh - 110px);
  margin-top: 10px;
  box-sizing: border-box;
  background-color: #fff;
  overflow: hidden;
}

.left-tree {
  display: inline-block;
  padding: 20px 15px 0 5px;
  height: 1200px;
  border-right: 1px solid #e6e6e6;
  box-sizing: border-box;
  position: relative;
}

/* todo layui-tree-entry 设置无效 */
.layui-tree-entry {
  position: relative;
  padding: 10px 0;
  height: 20px;
  line-height: 20px;
  white-space: nowrap;
}

.isFold {
  position: absolute;
  top: 36%;
  right: -10px;
  width: 26px;
  height: 26px;
  line-height: 26px;
  border-radius: 13px;
  background-color: #fff;
  border: 1px solid #e6e6e6;
  cursor: pointer;
}

.search-input {
  display: inline-block;
  width: 98%;
  margin-right: 10px;
}

.isChecked {
  display: inline-block;
  background-color: #e8f1ff;
  color: red;
}
.layui-tab-content{
  padding: 0;
}
</style>
