<template>
  <div>
    <MOSTY.PageTree :pageTitle="'培训计划'" :searchType="'01'" @getDeptId="getdeptId">
      <template #titleright>
        <div class="toggle" :class="{ active: isOpen }" @click="isOpen = !isOpen">
          <span>统计</span>
          <el-icon>
            <DArrowLeft />
          </el-icon>
        </div>
      </template>
      <template #serach>
        <section v-show='isOpen' ref="getHeight">
          <section class="box-sjtj">
            <MOSTY.Assort :title="'培训计划统计'" style="padding: 0;" />
            <section class="flex">
              <section class="left-tj">
                <Sjtj :info="countlist" :isShowTip="false" :isShowBottom="false" :width="400" mb="6px" />
              </section>
            </section>
          </section>
        </section>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
        <el-divider />
        <div class="btnBox">
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
          <el-button type="primary" @click="export2Excel" v-loading="excelLoading">
            <el-icon>
              <Download />
            </el-icon>
            <span>导出表格</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <section :style="{ 'height': totalHeight }">
          <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading"
            :isSelect="false" :isSort="true" @SortChange="SortChange" style="width: 100%;" actionsW="300">
            <template #state="{ row }">
              <dict-tag :options="D_TB_PXZT" :value="row.state" :tag="false" />
            </template>
            <template #actions="{ row }">
              <span class="operedit" v-if="row.state == '0000' && dept.ssbmid == row.planHostsDeptId"
                @click="handleChange(row)">
                <el-icon>
                  <EditPen />
                </el-icon>修改</span>
              <el-popconfirm v-if="(row.state == '0000' || row.state == '0001') && dept.ssbmid == row.planHostsDeptId"
                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)"><el-icon>
                  <Compass />
                </el-icon>详情</span>
              <span class="operdel" v-if="row.state == '0000' && dept.ssbmid == row.planHostsDeptId"
                @click="handledelde(row)"><el-icon>
                  <CircleClose />
                </el-icon>
                作废</span>
            </template>
          </MOSTY.Table>
        </section>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="pageConfiger" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
          </MOSTY.Pages>
        </div>

      </template>
    </MOSTY.PageTree>
    <!-- 作废原因 -->
    <el-dialog v-model="centerDialogVisible" title="作废原因" width="30%" align-center :before-close="xlosezfyy">
      <el-form :model="zffrom" ref="forms" label-position="right" label-width="85px" style='display:block'>
        <el-form-item label="作废原因:" prop="planInvalidReason"
          :rules="[{ required: true, message: '请输入作废原因', trigger: 'blur' }]">
          <el-input v-model="zffrom.planInvalidReason" placeholder="请输入作废原因" maxlength="500" style="margin-right: 10px"
            show-word-limit />
        </el-form-item>
        <el-form-item label="上传附件:">
          <MOSTY.Upload :widthNumber="800" :limit="3" :nopicer="true" :isImg="false" :ShowfileList="true"
            :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" v-model="zffrom.zffile" :showinput="false"
            :delrow="delrow"></MOSTY.Upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="baofeibtn(forms)">
            确定
          </el-button>
          <el-button @click="xlosezfyy">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增弹出框 -->
    <div v-if="addDiaShow" class="dialog-box">
      <Addpxjh :addobj="addobj" @changeAddVi="changeAddVi">
      </Addpxjh>
    </div>

  </div>
</template>

<script setup>
// 引入
import { onMounted, ref, getCurrentInstance, reactive, watch, nextTick } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { exportXlsx } from "@/excel/Export2Excel.js";
import Addpxjh from "./pxjhcoms/addpxjh.vue";
import { getItem } from "@/utils/storage";
import { filterYear } from "@/utils/auth.js";
import { getApi, deleteApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import Sjtj from '@/views/dataReportWork/aqjypx/components/sjtj.vue'
const { proxy } = getCurrentInstance();
const { D_TB_PXZT } = proxy.$dict("D_TB_PXZT");
const dept = ref(getItem("deptId"));
const forms = ref()
const centerDialogVisible = ref(false);
const isOpen = ref(false)
const tableloading = ref(false);
const excelLoading = ref(false);
const tableData = ref([]);
const addDiaShow = ref(false);
const zffrom = ref({})
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  planHostsDeptId: "",
  planName: "",
  year: new Date().getFullYear().toString()
});

const countlist = reactive([
  { title: '培训计划数', num: 0, dm: 'all', icon: 'ccss/icon_01.png' },
  { title: '实施数', num: 0, dm: 'yss', icon: 'ccss/icon_02.png' },
  { title: '未实施数', num: 0, dm: 'wss', icon: 'ccss/icon_03.png' },
  { title: '实施率', num: 0.00 + '%', dm: 'ssl', icon: 'ccss/icon_04.png' }
])
const searchArr = reactive([
  {
    showType: "input",
    prop: "planName",
    width: '250px',
    placeholder: '请输入计划名称'
  },
  {
    showType: "select",
    prop: "year",
    width: '250px',
    defaultVal: new Date().getFullYear(),
    options: filterYear(7),
  },
]);
const tableColumn = ref([
  {
    title: "计划名称",
    prop: "planName",
    sortable: true
  },
  {
    title: "计划时间",
    prop: "planImplementationDate",
    sortable: true
  },
  {
    title: "负责人",
    prop: "planChargePersonName",
    sortable: true
  },
  {
    title: "主办部门",
    prop: "planHostsDeptName",
    sortable: true
  },
  {
    title: "培训地点",
    prop: "place",
    sortable: true
  },
  {
    title: "培训人数",
    prop: "planTraineeNumber",
    sortable: true
  },
  {
    title: "课时(小时)",
    prop: "planClassHour",
    sortable: true
  },
  {
    title: "状态",
    prop: "state",
    slot: true,
    sortable: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
//表单参数
const addobj = ref({
  title: '新增',
  savebtnshow: true,
  id: null
})
const totalHeight = ref(null)
const getHeight = ref(null)
//统计
const fromObj = ref({
  orgcode: '',
  year: new Date().getFullYear().toString()
})
watch(() => isOpen.value, (val) => {
  nextTick(() => {
    if (val) {
      totalHeight.value = `calc(100vh - ${379 + getHeight.value.offsetHeight}px)`
      return
    }
    totalHeight.value = `calc(100vh - 379px)`
  })
}, {
  deep: true,
  immediate: true
})
onMounted(() => {
  nextTick(() => {
    totalHeight.value = `calc(100vh - ${379 + getHeight.value.offsetHeight}px)`
  })
});
//获取部门数据
const getdeptId = (val) => {
  fromObj.value.orgcode = val.id
  listQuery.value.planHostsDeptId = val.id;
  listQuery.value.orgname = val.orgname;
  listQuery.value.pageCurrent = 1;
  pageConfiger.pageCurrent = 1;
  getTableData();
  getcount()
};

//查询
function onSearch(obj) {
  listQuery.value.pageCurrent = 1;
  pageConfiger.pageCurrent = 1;
  listQuery.value.planName = obj.planName;
  listQuery.value.year = obj.year;
  fromObj.value.year = obj.year;
  getTableData();
  getcount()
}
//统计接口
function getcount() {
  getApi(fromObj.value, '/mosty-jcgl/training/getTbJhCount').then(res => {

    countlist[0].num = res.all;
    countlist[1].num = res.yss;
    countlist[2].num = res.wss;
    if (res.yss && res.all) {
      countlist[3].num = Math.floor((res.yss / res.all) * 100) + '%'
    } else {
      countlist[3].num = 0.00 + '%'
    }
  })
}


//作废
const baofeibtn = async (forms) => {
  if (!forms) return;
  await forms.validate((valid) => {
    if (valid) {
      zffrom.value.zffile = zffrom.value.zffile ? zffrom.value.zffile.toString() : null;
      if (zffrom.value) {
        postApi(zffrom.value, "/mosty-jcgl/training/cancellation").then((res) => {
          ElMessage.success("报废成功");
          centerDialogVisible.value = false
          getTableData();
          getcount()
        });
      }
    }
  });
};
//取消作废
function xlosezfyy() {
  zffrom.value.zffile = null;
  zffrom.value.planInvalidReason = null;
  zffrom.value.id = null;
  centerDialogVisible.value = false
}
//导出表格
const export2Excel = () => {
  excelLoading.value = true;
  let title = {
    planImplementationDate: "计划时间",
    planName: "计划名称",
    planChargePersonName: "负责人",
    planHostsDeptName: "主办部门",
    place: "培训地点",
    planTraineeNumber: "培训人数",
    planClassHour: "课时(小时)",
    states: "状态"
  };
  const data = {
    pageSize: 10000,
    pageCurrent: 1,
    year: listQuery.value.year,
    planHostsDeptId: listQuery.value.planHostsDeptId
  }
  getApi(data, "/mosty-jcgl/training/exportDataJh").then((res) => {
    if (res) {
      let data = res;
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].states = proxy.$getDictVal(data[i].state, D_TB_PXZT);
        }
        let tablename = `${listQuery.value.orgname}安全培训计划管理.xlsx`;
        exportXlsx(title, data, `${listQuery.value.orgname}安全培训计划表`, tablename);
      }
      excelLoading.value = false;
    }
    excelLoading.value = false;
  }).finally(() => {
    excelLoading.value = false;
  });
};
// 获取表格数据
const getTableData = () => {
  tableloading.value = true;
  getApi(listQuery.value, "/mosty-jcgl/training/getList")
    .then((res) => {
      if (res.records) {
        tableloading.value = false;
        tableData.value = res.records;
        pageConfiger.total = res.total;
      }
    })
    .finally(() => {
      tableloading.value = false;
    });
};

// 新增弹出框
const handleAdd = () => {
  addobj.value.title = "培训计划新增"
  addobj.value.savebtnshow = true
  addobj.value.id = null
  addDiaShow.value = true;
};

const handleSee = (row) => {
  addobj.value.title = "培训计划详情"
  addobj.value.savebtnshow = false
  addobj.value.id = row.id
  addDiaShow.value = true;
};
// 修改
const handleChange = (row) => {
  addobj.value.title = "培训计划调整"
  addobj.value.savebtnshow = true
  addobj.value.id = row.id
  addDiaShow.value = true;
};
//作废
const handledelde = (row) => {
  zffrom.value.id = row.id
  centerDialogVisible.value = true
};
//删除
const deldete = (row) => {
  deleteApi({}, `/mosty-jcgl/training/del/${row.id}`).then((res) => {
    ElMessage.success("删除成功");
    getTableData();
  });
};
// 控制新增弹出框的展示
const changeAddVi = (val) => {
  addDiaShow.value = val;
  addobj.value.title = ""
  addobj.value.savebtnshow = true
  addobj.value.id = null
  getTableData();
};

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

<style lang="scss" scoped>
.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}

.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);
    }
  }
}

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