<template>
  <div>
    <MOSTY.PageTree :pageTitle="'三级教育培训列表'" :searchType="'01'" @getDeptId="getdeptId">
      <template #titleright>
      </template>
      <template #serach>
        <div v-show="isOpen" ref="getHeight">
          <MOSTY.Assort title="三级教育培训统计" style="padding: 0;" />
          <section class="flex">
            <section class="left-tj">
              <Sjtj :info="countlist" :isShowTip="false" :isShowBottom="false" :width="236" mb="6px" />
            </section>
          </section>
        </div>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
        <el-divider />
        <section class="button">
          <el-button type="primary" @click="handleAddjhn">
            <el-icon>
              <Plus />
            </el-icon>
            <span>新增</span>
          </el-button>
          <el-button type="primary" class="ml6" @click="export2Excel" v-loading="excelLoading">
            <el-icon>
              <Download />
            </el-icon>
            <span>导出表格</span>
          </el-button>
        </section>
      </template>
      <template #table>
        <div :style="{ 'height': totalHeights }">
          <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading"
            :isSelect="false" :isSort="true" actionsW="250" style="width: 100%;">
            <template #level="{ row }">
              <dict-tag :options="D_BZ_LWJB" :value="row.level" :tag="false" />
            </template>
            <template #state="{ row }">
              <dict-tag :options="D_TB_PXZT" :value="row.state" :tag="false" />
            </template>
            <template #actions="{ row }">
              <span v-if="row.state == '0200' && row.type == '1' && row.planHostsDeptId == getItem('deptId').ssbmid"
                class="operedit" @click="handleChange(row, 'xg')"><el-icon>
                  <EditPen />
                </el-icon>修改</span>
              <el-popconfirm v-if="(row.state == '0200' || row.state == '0001') &&
                row.type == '1' && row.planHostsDeptId == getItem('deptId').ssbmid" confirm-button-text="是"
                cancel-button-text="否" icon-color="red" title="确定要删除?" @confirm="deldete(row)">
                <template #reference>
                  <span class="operdel" size="small"><el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
              <span class="operesee" @click="handleSee(row, 'see')"><el-icon>
                  <View />
                </el-icon>详情</span>
              <span v-if='row.ej && row.otherType == "09"' class="operedit" @click="handleChange(row, 'ej')"><el-icon>
                  <Compass />
                </el-icon>二级培训实施</span>
              <span v-if='row.sj && row.otherType == "09"' class="operedit" @click="handleChange(row, 'sj')"><el-icon>
                  <Compass />
                </el-icon>三级培训实施</span>
              <el-popconfirm
                v-if="row.state == '0200' && row.type == '1' && row.planHostsDeptId == getItem('deptId').ssbmid"
                confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要下发?" @confirm="xiafarow(row)">
                <template #reference>
                  <span class="operesee" size="small"><el-icon>
                      <Compass />
                    </el-icon>下发</span>
                </template>
              </el-popconfirm>
            </template>
          </MOSTY.Table>
        </div>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="pageConfiger" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
          </MOSTY.Pages>
        </div>
      </template>
    </MOSTY.PageTree>
    <!-- 新增弹出框 -->
    <div v-if="addDiaShow" class="dialog-box">
      <Addpxjhss :formData="formData" :type="types" @changeAddVi="changeAddVi">
      </Addpxjhss>
    </div>
    <!-- 计划外 -->
    <div v-if="addDiaShowjhw" class="dialog-box">
      <Addpxjhssjhw :formData="formData" :type="types" @changeAddVi="changeAddVijhw">
      </Addpxjhssjhw>
    </div>
    <!-- 详情 -->
    <div v-if="addDiaShowxq" class="dialog-box">
      <pxssxqdia :formData="formObj" :type="types" @changeAddVi="changexqclose" from="sjjypxss">
      </pxssxqdia>
    </div>

  </div>
</template>

<script setup>
// 引入
import { watch, onMounted, ref, getCurrentInstance, nextTick, reactive } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { exportXlsx } from "@/excel/Export2Excel.js";
import Addpxjhss from "./pxjhcoms/addpxss.vue";
import Addpxjhssjhw from "./pxjhcoms/addpxssjhw.vue";
import pxssxqdia from "./pxssxqdia.vue";
import { filterYear } from "@/utils/auth.js";
import { filterqx } from "@/utils/auth.js";
import { ElMessage } from "element-plus";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getItem } from "@/utils/storage";
import Sjtj from '@/views/dataReportWork/aqjypx/components/sjtj.vue'
const { proxy } = getCurrentInstance();

const orgLevel = ref(JSON.parse(window.localStorage.getItem("deptId")).orgLevel.substring(0, 1))
// 数据
const { D_TB_PXZT, GZ_TRAINOT, D_TB_PXJHLX, D_TB_YWLX } = proxy.$dict("D_TB_PXZT", "GZ_TRAINOT", "D_TB_PXJHLX", "D_TB_YWLX");
const tableloading = ref(false);
const addDiaShowxq = ref(false);
const types = ref(null);
const tableData = ref([]);
const formObj = ref({})
const searchArr = reactive([
  {
    showType: "select",
    prop: "year",
    width: '250px',
    defaultVal: new Date().getFullYear(),
    options: filterYear(7),
  },
  {
    showType: "input",
    prop: "planName",
    width: '250px',
    placeholder: '请输入项目名称'
  }
]);
const excelLoading = ref(false)
const formData = ref({
  title: '新增',
  saveBtnShow: true,
  id: null
})

const getHeight = ref(null)
const totalHeights = ref(null)
const isOpen = ref(false);
const countlist = ref(
  [
    { title: '培训实施数', num: 0, dm: 'ZZLLXX', icon: 'ccss/icon_01.png' },
    { title: '被实施数', num: 0, dm: 'FLFGXX', icon: 'ccss/icon_02.png' },
  ]
)
const tableColumn = ref([
  {
    title: "培训项目",
    prop: "planName",
    sortable: true
  },
  {
    title: "计划时间",
    prop: "planImplementationDate",

  },
  // {
  //   title: "开始时间",
  //   prop: "startDate",
  //   sortable: true
  // },
  // {
  //   title: "结束时间",
  //   prop: "finshDate",
  //   sortable: true
  // },
  {
    title: "主办部门",
    prop: "planHostsDeptName",
    sortable: true
  },
  {
    title: "培训地点",
    prop: "place",
    sortable: true
  },
  {
    title: "培训学时",
    prop: "planClassHour",
    sortable: true
  },
  {
    title: "培训人数",
    prop: "implementationTraineeNumber",
    sortable: true
  },
  {
    title: "项目负责人",
    prop: "planChargePersonName",
    sortable: true
  },
  {
    title: "状态",
    prop: "state",
    slot: true,
    sortable: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const handleTotal = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    totalHeights.value = `calc(100vh - 500px)`
  } else {
    totalHeights.value = `calc(100vh - 379px)`
  }
}
const pxlxlixt = ref([
  { value: '1', label: '计划内' },
  { value: '2,3', label: '计划外' },
  { value: '', label: '全部' },
])
// 分页
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  otherType: ['09'],
  planHostsDeptId: "",
  type: null,
  year: new Date().getFullYear().toString()
});
const total = ref(0);
const addDiaShow = ref(false);
const addDiaShowjhw = ref(false);
onMounted(() => {
  nextTick(() => {
    if (isOpen.value) {
      totalHeights.value = `calc(100vh - 500px)`
    } else {
      totalHeights.value = `calc(100vh - 379px)`
    }
  })
});
//获取部门数据
const getdeptId = (val) => {
  listQuery.value.planHostsDeptId = val.id;
  listQuery.value.pageCurrent = 1;
  getTableData();
  getcount()
};
// 选择框
watch(
  () => listQuery.value.year,
  (val) => {
    if (val) {
      getTableData();
      getcount()
    }
  }
);
//获取
function getcount() {
  let data = {
    orgcode: listQuery.value.planHostsDeptId,
    year: listQuery.value.year
  }
  getApi(data, '/mosty-jcgl/training/getTbSsCount').then(res => {
    countlist.value[0].num = res.jhl;
    countlist.value[1].num = res.bss;
  })
}
//查询
function onSearch(obj) {
  listQuery.value.year = obj.year;
  listQuery.value.planName = '';
  listQuery.value.pageCurrent = 1;
  getTableData();
}
// 控制新增与检查配置修改的标题
const title = ref("");

// 获取表格数据
const getTableData = () => {
  tableloading.value = true;
  postApi(listQuery.value, "/mosty-jcgl/training/getListPxss")
    .then((res) => {
      if (res.records) {
        tableloading.value = false;
        tableData.value = res.records;
        if (tableData.value) {
          tableData.value.forEach(async (item) => {
            if (item.otherType == '09') {
              let jbobj = await getsjData(item.id)
              item.sj = jbobj.sj
              item.ej = jbobj.ej
              item.oldejid = jbobj.ejid ? jbobj.ejid : null
              item.oldsjid = jbobj.sjid ? jbobj.sjid : null
            }
          })
        }
        pageConfiger.total = res.total;
      }
    })
    .catch((err) => {
      tableData.value = [];
      tableloading.value = false;
    }).finally(() => {
      tableloading.value = false;
    });
};
//获取三级培训信息
const getsjData = async (id) => {
  return new Promise(ok => {
    getApi({ id, year: listQuery.value.year }, '/mosty-jcgl/training/getSjpxDetail').then((res) => {
      ok(res ? res : [])
    })
  })
}

//导出表格
const export2Excel = () => {
  excelLoading.value = true
  let title = {
    planName: "培训项目",
    startDate: "开始时间",
    finshDate: "结束时间",
    planHostsDeptName: "主办部门",
    specialityType: "业务类型",
    types: "计划类型",
    otherTypes: "培训类型",
    contactorName: "联系人",
    contactorPhone: "联系人电话",
    planChargePersonName: "负责人",
    states: "状态",
  };
  const param = listQuery.value
  param.pageCurrent = 1
  param.pageSize = 1000
  postApi(param, "/mosty-jcgl/training/getListPxss").then((res) => {
    if (res) {
      let data = res.records;
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].types = data[i].type == '1' ? '计划内培训' : '计划外培训';
          data[i].states = data[i].state ? D_TB_PXZT.value.find(item => item.value == data[i].state).label : "";
          data[i].otherTypes = data[i].otherType ? GZ_TRAINOT.value.find(item => item.value == data[i].otherType).label : "";
          let specialityType = data[i].specialityType
          let sType = "";
          if (specialityType) {
            specialityType = specialityType.split(',')
            specialityType.map(item => {
              sType += D_TB_YWLX.value.find(v => v.value == item).label + "、"
            })
          }
          data[i].specialityType = sType
        }
        let tablename = "培训情况台账.xlsx";
        exportXlsx(title, data, '培训情况台账', tablename);
        excelLoading.value = false
      }
      excelLoading.value = false
    }
  }).catch(() => {
    excelLoading.value = false
  });
};

// 新增弹出框
const handleAddjhn = (val) => {
  formData.value.title = '三级教育培训新增'
  types.value = '1';
  formData.value.saveBtnShow = true
  formData.value.id = null
  formData.value.otherType = '09'
  tableloading.value = false;
  addDiaShow.value = true;
};
const handleAddjhw = () => {
  formData.value.title = '计划外培训实施'
  types.value = '2';
  formData.value.saveBtnShow = true
  formData.value.id = null
  tableloading.value = false;
  addDiaShowjhw.value = true;
};
//车辆培训==计划外
const handleSee = (row) => {
  types.value = row.type;
  var isTrue = false;
  //计划外没有三级培训
  getApi({ id: row.planHostsDeptId }, '/mosty-base/deptFeign/getOrgById').then(res => {
    formObj.value.orgLevel = res.orgLevel
    // 是否是安全部门
    if (filterqx('isaqbm') == '1') {
      if (res.orgLevel.substring(0, 1) == '1') {
        if (orgLevel.value == '1') {
          isTrue = true
        }
      } else if (res.orgLevel.substring(0, 1) == '2') {
        //当前登录部门orgLevel为1、2能看
        if (orgLevel.value == '1' || orgLevel.value == '2') {
          isTrue = true
        }
      } else if (res.orgLevel.substring(0, 1) == '3') {
        if (orgLevel.value == '1' || orgLevel.value == '2' || orgLevel.value == '3') {
          isTrue = true
        }
      }
    } else {
      isTrue = false
    }

    if (isTrue && row.otherType == "09") {
      formObj.value.sjtype = 'yj'
      formObj.value.title = '三级教育培训详情'
    } else {
      if (row.ej && row.otherType == "09") {
        //二级未实施
        formObj.value.sjtype = 'yj'
        formObj.value.title = '三级教育培训详情（一级培训）'
      } else if ((row.sj && row.otherType == "09") || row.oldejid) {
        //二级已实施，三级未实施
        formObj.value.sjtype = 'ej'
        formObj.value.title = '三级教育培训详情（二级培训）'
      } else if (row.oldsjid) {
        //三级已实施
        formObj.value.sjtype = 'sj'
        formObj.value.title = '三级教育培训详情（三级培训）'
      } else {
        formObj.value.sjtype = 'jc'
        formObj.value.title = '培训详情'
      }
    }
    formObj.value.id = row.id;
    formObj.value.state = row.state;
    formObj.value.oldejid = row.oldejid;
    formObj.value.type = row.type;
    formObj.value.title = row.planName
    addDiaShowxq.value = true
  })
};

function changexqclose() {
  formObj.value.id = null;
  formObj.value.type = null;
  addDiaShowxq.value = false
  getTableData();
}

// 修改
const handleChange = (row, val) => {
  formData.value.types = val
  types.value = row.type;
  if (row.type == "1") {
    if (val == 'xg') {
      formData.value.title = '培训计划内修改'
    } else if (val == 'ej') {
      formData.value.title = '实施二级培训'
      formData.value.planName = row.planName
    } else if (val == 'sj') {
      formData.value.title = '实施三级培训'
      formData.value.planName = row.planName
      formData.value.oldejid = row.oldejid
      formData.value.planHostsDeptId = row.planHostsDeptId
    }
    //计划内
    formData.value.saveBtnShow = true
    formData.value.id = row.id;
    addDiaShow.value = true;

  } else {
    if (val == 'xg') {
      formData.value.title = '培训计划外修改'
    } else if (val == 'ej') {
      formData.value.title = '实施二级培训'
      formData.value.planName = row.planName
    } else if (val == 'sj') {
      formData.value.title = '实施三级培训'
      formData.value.planName = row.planName
      formData.value.oldejid = row.oldejid
      formData.value.planHostsDeptId = row.planHostsDeptId
    }


    formData.value.saveBtnShow = true
    formData.value.id = row.id
    addDiaShowjhw.value = true;
  }


};
//作废
const handledelde = (row) => {
  if (row.type == "1") {
    types.value = row.type;
    formData.value.title = '培训计划作废'
    formData.value.saveBtnShow = false
    formData.value.id = row.id;
    addDiaShow.value = true;
  } else {
    formData.value.title = '培训计划外作废'
    formData.value.saveBtnShow = false
    formData.value.id = row.id
    addDiaShowjhw.value = true;
  }

  types.value = row.type;

  title.value = "是否作废该培训？请填写作废原因";
};
//删除
const deldete = (row) => {
  postApi({}, `/mosty-jcgl/training/pxssDelJhn/${row.id}`).then((res) => {
    ElMessage.success("删除成功");
    getTableData();
  });
};
//下发
const xiafarow = (row) => {
  postApi({}, `/mosty-jcgl/training/pxssIssue/${row.id}`).then((res) => {
    ElMessage.success("下发成功");
    getTableData();
  });
};
// 控制新增弹出框的展示
const changeAddVi = (val) => {
  addDiaShow.value = val;
  formData.value.title = ''
  formData.value.saveBtnShow = true
  formData.value.id = null;
  formData.value.planName = null;
  formData.value.types = null;
  types.value = null;
  getTableData();
};
const changeAddVijhw = (val) => {
  addDiaShowjhw.value = val;
  formData.value.title = ''
  formData.value.saveBtnShow = true
  formData.value.id = null;
  formData.value.planName = null;
  formData.value.types = null;
  types.value = null;
  getTableData();
};

//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.value.pageCurrent = val;
  getTableData();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.value.pageSize = val;
  getTableData();
};
</script>

<style lang="scss" scoped>
.toggle {
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #0f3916;

  .el-icon {
    transform: rotate(90deg);
    transition: all 0.25s ease;
  }

  &.active {
    .el-icon {
      transform: rotate(-90deg);
    }
  }
}

.flex {
  display: flex;
  align-items: center;

  .left-tj {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: start;
  }
}

.query-flex {
  display: flex;
  justify-content: space-between;

  .query-section {

    width: 68%;
  }

  .query-btn {
    width: 360px;
    display: flex;
    justify-content: end;

    .toggle {
      height: 32px;
      cursor: pointer;
      display: flex;
      align-items: center;
      color: #0f3916;

      .el-icon {
        transform: rotate(90deg);
        transition: all 0.25s ease;
      }

      &.active {
        .el-icon {
          transform: rotate(-90deg);
        }
      }
    }
  }
}

.button {
  display: flex;
  align-items: center;
  justify-content: end;
  margin-bottom: 12px;
}

::v-deep .el-form-item {
  margin: 9px !important;
}
</style>
