
<script lang="ts">
export default {
  name: 'visionScreening' // 视力普查
};
</script>
<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import Page from '@/components/Pagination/page.vue';
import { queryRegion } from "@/api/regionmodule/region";
import { queryVisionExamineItemList,queryExaminePlanPage,addExaminePlan,updateExaminePlan,delExaminePlan,queryPlanNum,getPlanCode } from "@/api/planscreening";
import { querySchoolList } from "@/api/regionmodule/school";
import Planmanage from "./planmanage.vue";
import Viewreport from "./viewreport.vue";
import { publicTree } from '@/utils/validate';
const queryInfo :any = ref({
  current:1,
  size:10,
  total:0
})
const planName = ref('')
const org_name = ref('')
const tableData = ref([])
const dialogFormVisible = ref(false)
const dialogtitle = ref('新增普查计划')
const form:any = ref({})
const planform = ref();
const moduleinfo1 = ref(true);
const moduleinfo2 = ref(false);
const moduleinfo3 = ref(false);
const moduleinfo4 = ref(false);
const rules = reactive<FormRules>({
  plan_code: [{ required: true, message: "请输入计划代码", trigger: "blur" }],
  plan_name: [{ required: true, message: "请输入计划名称", trigger: "blur" }]
});
const planYear:any = ref()
const planCode = ref("")
const tempName = ref("")
//获取学年
function getYear(){
    var date = new Date();
    var year = date.getFullYear();
    var month:any = date.getMonth() + 1;
    if(month >= 3 && month < 9){
      planYear.value = (year - 1)+'-' + '2'
      planCode.value = (year - 1) + '02'
      tempName.value = (year - 1) + '年第二学期'
    }else{
      planYear.value = year + '-'+ '1'
      planCode.value = year + '01'
      tempName.value = year + '年第一学期'
    }


    // 拼接
    
}
const org_id =ref("")
function addinfo(){
  getYear()
  dialogtitle.value = '新增计划'
  form.value = {}

  
  isSwitch.value = false
  dialogFormVisible.value = true
}
function editinfo(row:any){
 form.value = JSON.parse(JSON.stringify(row)) 
 examItemsData.value = []
 if(form.value.exam_items != ""){
    let examItemsArr = JSON.parse(form.value.exam_items)
    for(let j=0;j<examItemsArr.length;j++){
      examItemsData.value.push(examItemsArr[j].code +',' + examItemsArr[j].name)
    }
 }
 
 isSwitch.value = false
 dialogtitle.value = '修改普查计划'
 dialogFormVisible.value = true
}
const isSwitch = ref(false)
function infosubmit(formEl: any){
  formEl.validate((valid: any) => {
    if (valid) {
      if(examItemsData.value.length ==0){
        ElMessage({
            message: "请选择筛查项目！",
            type: "warning",
          });
        return
      }
      if(form.value.org_name =='' || form.value.org_name ==null ){
        ElMessage({
            message: "请选择组织机构！",
            type: "warning",
          });
        return
      }

      if(isSwitch.value == true){
        return
      }
      isSwitch.value = true
      let tempData:any = []
      for(let i=0;i<examItemsData.value.length;i++){
        tempData.push({
          code:examItemsData.value[i].split(',')[0],
          name:examItemsData.value[i].split(',')[1]
        })
      }
      if (form.value.id) {
        const data:any = {
          id:form.value.id,
          orgId: form.value.org_id,
          orgName: form.value.org_name,
          orgType: form.value.org_type,
          planCode: form.value.plan_code,
          planName: form.value.plan_name, 
          planYear: form.value.plan_year, 
          examType: "01", //普查
          visInstIds:"",
          examItems:JSON.stringify(tempData),
          planStartDate:form.value.plan_start_date,
          planEndDate:form.value.plan_end_date,
        };
        updateExaminePlan(data).then((item) => {
          dialogFormVisible.value = false;
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          getData();
        }).catch(()=>{
          isSwitch.value = false
        })
      } else {
        const data:any = {
          orgId: form.value.org_id,
          orgName: form.value.org_name,
          orgType: form.value.org_type,
          planCode: form.value.plan_code,
          planName: form.value.plan_name, 
          planYear: form.value.plan_year, 
          examType: "01", // 5- 学校
          visInstIds:"",
          examItems:JSON.stringify(tempData),
        };
        addExaminePlan(data).then((item) => {
          dialogFormVisible.value = false;
          getData();
          ElMessage({
            message: "新增成功",
            type: "success",
          });
        }).catch(()=>{
          isSwitch.value = false
        })
      }
 
    }
  })
}
function delinfo(row: any) {
  ElMessageBox.confirm("确定删除此普查计划吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let params = {
      ids: row.id,
    };
    delExaminePlan(params).then((res:any) => {
     
      if( res.code == '0'){
        getData();
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }
      
    });

  });
}
const loading =ref(false)
function getData(){

  let params = {
    planName: planName.value,
    orgName: org_name.value,
    examType:'01',
    current: queryInfo.value.current,
    size:queryInfo.value.size
  };
  params.planName = planName.value.replace(/\s+/g, "");
  params.orgName = org_name.value.replace(/\s+/g, "");
  loading.value = true
  queryExaminePlanPage(params).then((res:any) => {
    tableData.value = res.data.records;
    for(let i=0;i<res.data.records.length;i++){
      if(res.data.records[i].exam_items != null && res.data.records[i].exam_items != ''){
        let examItemsArr = JSON.parse(res.data.records[i].exam_items)
        let examItemsTemp  = []
        for(let j=0;j<examItemsArr.length;j++){
          examItemsTemp.push(examItemsArr[j].name)
        }
        res.data.records[i].examItems = examItemsTemp.join("、")
      }
    }
    queryInfo.value.total = res.data.total
    loading.value = false
  });
}
function planclick(row:any){
  form.value = row
  moduleinfo1.value = false
  moduleinfo2.value = true
  moduleinfo3.value = false
}
function viewreportclick(row:any){
  form.value = row
  moduleinfo1.value = false
  moduleinfo2.value = false
  moduleinfo3.value = true
}
function handleClose(){
  if (planform.value != null) planform.value.resetFields();
  dialogFormVisible.value = false
}
function returnClick(){
  moduleinfo1.value = true
  moduleinfo2.value = false
  moduleinfo3.value = false
}
function reportreturnClick(){
  moduleinfo1.value = true
  moduleinfo2.value = false
  moduleinfo3.value = false
}
const VisionExamineItemList:any = ref([])
const examItemsData:any =ref([])
function cityChange(e:any){
}
onMounted(() => {
  queryVisionExamineItemList({}).then((res) => {
    VisionExamineItemList.value = res.data;
    for(let i=0;i<res.data.length;i++){
        if(i<2){
          examItemsData.value.push(res.data[i].item_code +',' + res.data[i].item_name)
        }
    }

   
  });
  getData();
});

const dialogVisible = ref(false)
function viewOrg(){
  SchoolData.value = []
  getTree()
  dialogVisible.value = true
}
function regionClose(){
  dialogVisible.value = false
}
//树形控件类型定义
interface Tree {
  [x: string]: any;
  label: string;
  children?: Tree[];
}
//搜索内容
const regionName = ref("");
const orgId = ref("")
const orgName = ref("")
const orgType = ref("")
// 左侧树
const treedata: any = ref([]);
const defaultProps = { label: "name" };
const handleNodeClick = (data: Tree) => {
  orgId.value = data.id;
  orgName.value = data.custom1
  orgType.value = data.type
  getSchoolData()
  // getData();
};
const schoolClick = (data: Tree) => {
  orgId.value = data.id;
  orgName.value = data.name
  orgType.value = '5'
};

function confirmsubmit(){
  queryPlanNum({planYear:planYear.value,examType:"01",orgid:orgId.value}).then((res:any) => {
    if(res.code == 0){
      if(res.data>8){
        planCode.value = planCode.value + (res.data+1)
      }else{
        planCode.value = planCode.value +"0" +""+  (res.data+1)
      }
        tempName.value = tempName.value + '第'+(res.data+1) +'次视力筛查'
        form.value.plan_name = tempName.value
        // form.value.plan_code = planCode.value
        form.value.org_id =  orgId.value 
        form.value.org_name =  orgName.value 
        form.value.org_type=  orgType.value
        if(orgName.value != null){
          form.value.plan_name = orgName.value.replace(/\s*/g,"")+'-' + tempName.value
        }else{
          form.value.plan_name =  tempName.value
        }
    }
  })
  getPlanCode({planYear:planYear.value,examType:"01"}).then((res:any) => {
    form.value.plan_code = res.data
  })
  form.value.plan_year = planYear.value 
  dialogVisible.value = false
}

const treeloading =ref(false)
const tempData = ref([])
//获取行政区域
function getTree() {
  const params = {
    name: regionName.value,
    status:'01'
  };
  treeloading.value = true
  queryRegion(params).then((res: any) => {
    orgName.value = ""
    orgId.value = ""
    orgType.value = ""
    tempData.value =  JSON.parse(JSON.stringify(res.data)) 
    treedata.value = publicTree(res.data,"")
    treeloading.value = false
  })
  .catch((error:any)=>{
    treeloading.value = false
  })
}
const SchoolData = ref([])
const schoolloading =ref(false)
//获取医生列表
function getSchoolData() {
  if(orgId.value == ''){
    SchoolData.value = []
    return
  }
  schoolName.value = schoolName.value.replace(/\s+/g, "");
  let params = {
    name: schoolName.value,
    regionId: orgId.value,
    type:orgType.value
  };
  schoolloading.value = true
  querySchoolList(params).then((res) => {
    SchoolData.value = res.data;
    schoolloading.value = false
  }).catch(()=>{
    schoolloading.value = false
  });
}
function searchInit(){
  treedata.value = publicTree(tempData.value,regionName.value)
}
const schoolName = ref("")
function searchSchoolInit(){
  getSchoolData()
}
</script>

<template>
    <div v-show="moduleinfo1" class="w-full">
      <div v-show="moduleinfo1" class="visionscreening-box">
        <div class="visionscreening-box-top">
          <div class="flex">
            <el-input v-model="planName" style="width:200px" placeholder="请输入计划名称" clearable />
            <el-input v-model="org_name" style="width:200px;margin-left:10px" placeholder="请输入组织机构名称" clearable />
            <el-button type="primary" class="ml-[10px]" @click="getData">搜索</el-button>
          </div>
          <el-button type="primary" @click="addinfo"><img src="@/assets/visionscreening/jscz_xz.png" alt="" style="margin-right: 4px;" >新增普检计划</el-button>
        </div>
        <div class="visionscreening-box-bottom">
          <el-table :data="tableData" border style="width: 100%; height:calc(100vh - 290px)" :header-cell-style="{background:'rgb(250 250 250)',height:'50px'}">
            <el-table-column prop="plan_code" label="计划编号" width="120" />
            <el-table-column prop="plan_name" label="计划名称" width="180">
              <template #default="scope">
                <div v-if="scope.row.display ==true" style="display: flex;align-items: center;">
                  <div style="margin-right:10px ;">{{ scope.row.plan_name }}</div>
                  <img src="@/assets/tableicon/u4891.svg" alt="" >
                </div>
                <span v-else>{{ scope.row.plan_name }}</span>
                
              </template>
            </el-table-column>
            <el-table-column prop="plan_year" label="计划学年" width="100" />
            <el-table-column prop="examItems" label="筛查项目" />
            <el-table-column prop="org_name" label="组织机构" width="120"/>
            <el-table-column prop="org_type" label="机构类型" width="120" align="center" >
              <template #default="scope">
                <span v-if="scope.row.org_type =='2'">省/直辖市</span>
                <span v-if="scope.row.org_type =='3'">市/自治州</span>
                <span v-if="scope.row.org_type =='4'">区/县/县级市</span>
                <span v-if="scope.row.org_type =='5'">学校</span>
              </template>
            </el-table-column>
            <el-table-column prop="plan_start_date" width="120" label="开始日期"  align="center"/>
            <el-table-column prop="plan_end_date" width="120" label="结束日期"  align="center"/>
            <el-table-column prop="status" width="100" label="状态"  align="center">
            <template #default="scope">
                <span v-if="scope.row.status === '01'" style="color:#409EFF">初始创建</span>
                <!-- <span v-else-if="scope.row.status === 1" style="color:#FF9900">筛查中</span> -->
                <span v-else style="color:#009966">筛查完成</span>
            </template>
            </el-table-column>
            <el-table-column prop="address" width="120" label="完成日期" />
            <el-table-column prop="address" label="操作" width="140" fixed="right" align="center">
              <template #default="scope">
                <div style="display: -webkit-flex;display: flex; justify-content: space-around;-webkit-justify-content: space-around; ">
                  <img src="@/assets/MenuIcon/lbcz_xg.png" alt="" title="修改" @click="editinfo(scope.row)" style="cursor: pointer;">
                  <img src="@/assets/visionscreening/bg-jhgl.png" alt="" title="计划管理" @click="planclick(scope.row)" style="cursor: pointer;">
                  <img src="@/assets/visionscreening/bg-ckbg.png" alt="" title="查看报告" @click="viewreportclick(scope.row)" style="cursor: pointer;">
                  <img src="@/assets/MenuIcon/lbcz_sc.png" alt="" title="删除" @click="delinfo(scope.row)" style="cursor: pointer;">
                </div>
              </template>
            </el-table-column>
          </el-table>
          <Page class="mt-[20px]" :total="queryInfo.total" v-model:size="queryInfo.size" v-model:current="queryInfo.current"
          @pagination="getData" />
        </div>
      </div>
      
      <el-dialog v-model="dialogFormVisible" :close-on-click-modal="false" :title="dialogtitle" :before-close="handleClose" width="620px" draggable append-to-body>
        <el-form ref="planform" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="组织机构">
          <el-input v-if="form.id==null" v-model="form.org_name" autocomplete="off" placeholder="请输入组织机构" disabled style="width: 390px;" />
          <el-button  v-if="form.id==null" type="primary" class="ml-[5px]" @click="viewOrg">选择</el-button>
          <el-input v-if="form.id!=null" v-model="form.org_name" autocomplete="off" placeholder="请输入组织机构" disabled style="width: 100%;" />
        </el-form-item>
        <el-form-item label="计划学年">
          <el-input v-model="form.plan_year" autocomplete="off" placeholder="请输入计划学年" disabled/>
        </el-form-item>
        <el-form-item label="计划名称" prop="plan_name">
          <el-input v-model="form.plan_name" autocomplete="off" placeholder="请输入计划名称" />
        </el-form-item>
       
        <el-form-item label="筛查项目">
          <el-checkbox-group v-model="examItemsData" @change="cityChange">
            <el-checkbox v-for="city in VisionExamineItemList" :label="city.item_code +',' + city.item_name" :key="city.item_code">
              {{ city.item_name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="机构类型">
          <el-radio-group v-model="form.org_type" disabled>
            <el-radio :label="'2'" size="large">省/直辖市</el-radio>
            <el-radio :label="'3'" size="large">市/自治州</el-radio>
            <el-radio :label="'4'" size="large">区/县/县级市</el-radio>
            <el-radio :label="'5'" size="large">学校</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始日期">
            <el-date-picker v-model="form.plan_start_date" type="date" style="width:100%" placeholder="请输入开始日期"/>
        </el-form-item>
        <el-form-item label="结束日期">
            <el-date-picker v-model="form.plan_end_date" type="date" style="width:100%" placeholder="请输入结束日期"/>
        </el-form-item>
        </el-form>
        <span class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="infosubmit(planform)">确定</el-button>
        </span>
      </el-dialog>

      <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :title="'查看组织机构'" 
      :before-close="regionClose" width="620px" draggable append-to-body>
        <div class="tscheck" style="display: flex;justify-content: space-between;">
          <div class="leftbox" style="width: 100%;">
            <div class="lefttitle">
              <div class="line"></div>
              <div class="treetitle">行政区域</div>
            </div>
            <el-input v-model="regionName" placeholder="请输入行政区域" clearable style="width: 500px;margin-left: 10px;margin-bottom: 10px;" 
            @input="searchInit" />
            <el-tree v-loading="treeloading" 
              ref="treeRef" node-key="id" :data="treedata"  :props="defaultProps"
              :expand-on-click-node="false"
              @node-click="handleNodeClick" style="height: calc(100vh - 320px); overflow: auto;margin-left: 10px;">
              <template #default="{ node, data }">
              <span class="custom-tree-node">
                <el-radio v-model="orgId" :label="data.id">{{ node.label }}</el-radio>
              </span>
            </template>
            </el-tree>
          </div>
          <!-- <div class="leftbox" style="margin-left: 20px;width: 300px;">
            <div class="lefttitle">
              <div class="line"></div>
              <div class="treetitle">学校</div>
            </div>
            <el-input v-model="schoolName" placeholder="请输入学校名称" clearable style="width: 230px;margin-left: 10px;margin-bottom: 10px;" 
             @keyup.enter="searchSchoolInit" />
            <el-tree v-loading="schoolloading" default-expand-all
              node-key="id" :data="SchoolData"  :props="defaultProps"
              :expand-on-click-node="false"
              @node-click="schoolClick" style="height: calc(100vh - 320px); overflow: auto;margin-left: 10px;">
              <template #default="{ node, data }">
              <span class="custom-tree-node">
                <el-radio v-model="orgId" :label="data.id">{{ node.label }}</el-radio>
              </span>
            </template>
            </el-tree>
          </div> -->
        </div>
        <div>
        </div>
        <span class="dialog-footer" style="margin-top:10px ;margin-right:10px">
            <el-button @click="regionClose">取消</el-button>
            <el-button type="primary" @click="confirmsubmit">确定</el-button>
        </span>
      </el-dialog>
    </div>
    <Planmanage v-if="moduleinfo2" :planInfo="form" @returnClick="returnClick" />
    <Viewreport v-if="moduleinfo3" :planInfo="form" @reportreturnClick="reportreturnClick" />
</template>
<style scoped  lang="scss">

.visionscreening-box {
  height: calc(100vh - 130px);
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0px 0px 10px rgba(219, 225, 236, 1);
  padding: 20px;
  .visionscreening-box-top{
    width:100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    // :deep(){
    //     .el-input{
    //         height:40px;
    //         line-height: 40px;
    //         width: 240px;
    //     }
    //     .el-button{
    //       height:40px; 
    //     }
    // }
  }
}
.dialog-footer {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
}
// :deep(){
//    .el-input{
//     height: 40px;
//     line-height: 40px;
//    }
//    .el-form-item--default .el-form-item__label{
//     height: 40px;
//     line-height: 40px;
//    }
// }
:deep(.el-tree-node__content){
  height: 30px;
 
}
// :deep(.el-tree-node.is-current > .el-tree-node__content){
//   background-color: transparent !important;
// }
.lefttitle {
  min-width: 150px;
  display: flex;
  align-items: center;
  padding: 10px 15px;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
  font-weight: 700;
  font-style: normal;
  font-size: 16px;
  color: #1B1B1B;
  background: rgba(246, 247, 250, 1);
  border-bottom: 1px var(--el-border-color) var(--el-border-style);
  margin-bottom: 10px;
  .line{
    border-width: 0px;
    width: 5px;
    height: 14px;
    margin-right: 7px;
    background: inherit;
    background-color: rgba(64, 158, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
  }
}
.leftbox{
  width: 250px;
  height: calc(100vh - 200px);
  border: 1px solid #e1e1e1;
  border-radius: 4px;
}
.tscheck {
  :deep(){
  .el-radio__input.is-checked+.el-radio__label{
   color: #fff !important; 
  }
  .el-radio__input.is-checked .el-radio__inner{
  border: 1px solid #fff;
}

}
}

</style>
