<template>
  <div>
    <MOSTY.PageTree :pageTitle="'工作计划(要点)信息表'" :searchType="'03'" @getDeptId="getdeptData">
      <template #serach>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" @submit="onSearch">
          <template #searbox>
            <el-radio v-model="listQuery.type" label="01" @change="typeChange">上级</el-radio>
            <el-radio v-model="listQuery.type" label="02" @change="typeChange">本级</el-radio>
          </template>
        </MOSTY.Search>
        <el-divider />
        <div class="btnBox">
          <el-button type="primary" @click="addShow" class="mr10">
            <!-- v-if="addShows" -->
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
          <el-button type="primary" @click="addfile">
            <span>年度工作要点附件</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <!-- 表格 -->
        <section class="eltab9">
          <MOSTY.Table :table-columns="pageData.tableColumns" :tableData="pageData.tableData"
            :tableloading="tableloading" :tableHeight="'100%'" :isSelect="false" style="width: 100%;" :isSort="false">
            <template #state="{ row }">
              <span v-if="row.state == '0'">未上报</span>
              <span v-else-if="row.state == '1'">等待{{ row.judgeUsername }}审核中</span>
              <span v-else-if="row.state == '2'">审核通过</span>
              <span v-else-if="row.state == '3'">审核不通过</span>
            </template>
            <template #actions="{ row }">
              <span class="operedown" v-if="row.deptCode == ssbmId && (row.state == '0' || row.state == '3')"
                size="small" @click="handlefb(row)">
                <!-- row.deptCode == ssbmId && ( -->
                <el-icon>
                  <Position />
                </el-icon>报送</span>
              <span class="operedit" v-if="row.state == '0' || row.state == '3'" @click="handlexg(row)">
                <!-- row.deptCode == ssbmId && ( -->
                <el-icon>
                  <EditPen />
                </el-icon>修改</span>
              <el-popconfirm v-if="row.state == '0' || row.state == '3'" confirm-button-text="是" cancel-button-text="否"
                icon-color="red" title="确定要删除?" @confirm="handledelete(row)">
                <!-- (row.deptCode == ssbmId || filterqx('saqbm') == '1') && -->
                <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>
            </template>
          </MOSTY.Table>
          <div class="fenye">
            <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
              @changeSize="handleSizeChange" />

          </div>
        </section>
      </template>
    </MOSTY.PageTree>


    <!-- 新增工作计划 -->
    <div v-if="addplanShow" class="dialog-box">
      <Addplan @close="closeAdd" v-if="addplanShow" :title="title" :id="rowId" :saveBtnShow="saveBtnShow"
        :Plantype="Plantype" :rwid="rwid" />
    </div>
    <div v-if="wcplanShow" class="dialog-box">
      <Wcplan @close="closeAdd" v-if="wcplanShow" :title="title" :id="rowId" :saveBtnShow="saveBtnShow"
        :Plantype="Plantype" :xplanId="xplanId" :rwid="rwid" />
    </div>
    <el-dialog v-model="dialogVisible" :title="titles" :before-close="CloseEvent" width="650px">
      <div>
        <el-form :model="addobj" label-width="129px" ref="frombt" :rules="rules" :disabled="!saveBtnShowfil">
          <el-form-item label="最后上报时间：" prop="dueTime">
            <el-date-picker v-model="addobj.dueTime" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              style='width:420px;' />
          </el-form-item>
          <el-form-item label="上传附件：" prop="file" label-width="129px">
            <MOSTY.Upload :isAutoWidth="true" :limit="1" :nopicer="true" :isImg="false" :ShowfileList="true"
              v-model="addobj.file" :showinput="true" :delrow="delrow" :keys="key" @filehandleChange="changeFile1"
              :placeholder="'请上传pdf,ofd, doc, docx,wps'" :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']">
            </MOSTY.Upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">

          <el-button type="primary" @click="searchfrom(frombt)" :loading="loading">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button @click="CloseEvent"> <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span></el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入
import { onMounted, reactive, ref, watch, getCurrentInstance } from "vue";
import { filterYear, filterqx } from "@/utils/auth.js";
import Addplan from "./compon/Addplan.vue";
import { ElMessage } from "element-plus";
import { getItem } from "@/utils/storage";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { useRoute } from "vue-router";
import Wcplan from "./compon/Wcplan.vue";
const { proxy } = getCurrentInstance();
const xplanId = ref(null)//计划小项id
const Plantype = ref('add')
const rwid = ref(null)
const searchArr = reactive([
  {
    showType: "select",
    prop: "planYear",
    defaultVal: new Date().getFullYear(),
    width: '250px',
    options: filterYear(7),
  },
  // {
  //   showType: "radio",
  //   label: "类型：",
  //   prop: "type",
  //   defaultVal: '01',
  //   width: '250px',
  //   options: [
  //     {
  //       value: '01',
  //       label: "上级"
  //     },
  //     {
  //       value: '02',
  //       label: "本级"
  //     }
  //   ],
  // }
]);
const rules = reactive({
  dueTime: [{ required: true, message: '请选择最后上报时间', trigger: 'blur' }],
  file: [{ required: true, message: '请选择附件', trigger: 'blur' }],
})
const route = useRoute();
// 数据
const addobj = ref({})
const frombt = ref()
const rowId = ref(null)
const addplanShow = ref(false);
const wcplanShow = ref(false);
const title = ref(""); //弹窗标题
const tableloading = ref(false)
const loading = ref(false)
const dialogVisible = ref(false)
const saveBtnShowfil = ref(false)
const saveBtnShow = ref(true);
const addShows = ref(false)
const titles = ref('')
// 分页
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 20,
  orgCode: "",
  type: "01",
  planYear: new Date().getFullYear()
});
const ssbmId = ref(getItem("deptId").ssbmid);
const userId = getItem("USERID")
console.log(userId, 'userId');

console.log(ssbmId.value, 'deptId');

const pageData = reactive({
  tableColumns: [
    {
      title: "计划年度",
      prop: "planYear"
    },
    {
      title: "计划名称",
      prop: "planName"
    },
    {
      title: "所属单位",
      prop: "orgName"
    },
    {
      title: "编制人",
      prop: "summaryUserName"
    },
    {
      title: "审批人",
      prop: "judgeUsername"
    },
    {
      title: "审批时间",
      prop: "judgeTime"
    },
    {
      title: "状态",
      prop: "state",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      slot: true
    }
  ],
  pageConfiger: {
    pageSize: 20,
    pageCurrent: 1,
    total: 0
  },
  tableData: []
})
// 初始化
onMounted(() => {
  examinel()
});
const typeChange = (val) => {
  listQuery.type = val
  listQuery.pageCurrent = 1;
  pageData.pageConfiger.pageCurrent = 1
  getListData()
}
function onSearch (obj) {
  listQuery.planYear = obj.planYear
  // listQuery.type = obj.type
  listQuery.pageCurrent = 1;
  pageData.pageConfiger.pageCurrent = 1
  getListData()
}
//获取列表数据
function getListData () {
  tableloading.value = true
  postApi(listQuery, "/mosty-jcgl/plansummary/getPlanSummary").then((res) => {
    if (res.records) {
      tableloading.value = false;
      pageData.tableData = res.records
      pageData.pageConfiger.total = res.total
    } else {
      pageData.tableData = []
      tableloading.value = false;
    }
    console.log(pageData.tableData, '列表数据');

  }).catch(err => {
    tableloading.value = false;
  }).finally(() => {
    tableloading.value = false;
  });
}


//获取默认部门
const getdeptData = (val) => {

  if (getItem("deptId").ssdwid.replace("XN", "") == val.orgcode.replace("XN", "") && filterqx('isaqbm') == '1') {
    addShows.value = true
  } else {
    addShows.value = false
  }
  listQuery.orgCode = val.id;
  listQuery.pageCurrent = 1;
  pageData.pageConfiger.pageCurrent = 1
  getListData();
}
function addfile () {
  //只有省公司并且是安全部门才能新增、修改【年度工作要点附件】
  if (filterqx('saqbm') == '1') {
    titles.value = '新增年度工作要点附件'
    getfile()
    saveBtnShowfil.value = true
  } else {
    //安全部门只能增删改工作计划以及查看工作要点附件
    titles.value = '查看年度工作要点附件'
    getfile()
    saveBtnShowfil.value = false
  }
  dialogVisible.value = true;
}
//对接查询本年度年度工作要点附件接口
function getfile () {
  getApi({}, '/mosty-jcgl/summaryFile/getSummaryFile').then(res => {
    if (res) {
      addobj.value = res ? res : null
    } else {
      addobj.value = {}
    }

  })
}
//保存工作年度要点附件
const searchfrom = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true
      addobj.value.file = addobj.value.file ? addobj.value.file.toString() : null
      getApi(addobj.value, '/mosty-jcgl/summaryFile/setSummaryFile').then(res => {
        loading.value = false
        dialogVisible.value = false;
        ElMessage.success("新增成功");
      }).catch((err) => {
        loading.value = false;
      })
    } else {
      return false;
    }
  });
};
//上报
function handlefb (row) {
  rowId.value = row.id
  Plantype.value = 'baos'
  title.value = "工作计划(要点)报送";
  addplanShow.value = true;
  saveBtnShow.value = true;
}
//取消
function CloseEvent () {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      dialogVisible.value = false;
    })
    .catch(() => {
      // catch error
    })

}
//新增
const addShow = () => {
  rowId.value = null
  Plantype.value = 'add'
  addplanShow.value = true;
  title.value = "工作计划(要点)新增";
  saveBtnShow.value = true;
};
//修改
const handlexg = (row) => {
  rowId.value = row.id
  Plantype.value = 'edit'
  title.value = "工作计划(要点)修改";
  addplanShow.value = true;
  saveBtnShow.value = true;

};
//详情
const handleSee = (row) => {
  rowId.value = row.id
  Plantype.value = 'seexq'
  title.value = "工作计划(要点)详情";
  addplanShow.value = true;
  saveBtnShow.value = false;

};
//审核
const examinel = () => {
  if (route.query.ywid) {
    rwid.value = route.query.rwid
    if (route.query.rwlx == '46') {
      rowId.value = route.query.ywid
      Plantype.value = 'senh'
      title.value = "工作计划(要点)审核";
      addplanShow.value = true;
      saveBtnShow.value = false;
    } else {
      rowId.value = route.query.ywid
      xplanId.value = route.query.p1
      Plantype.value = 'wczj'
      title.value = '完成年度工作计划(要点)';
      saveBtnShow.value = false;
      wcplanShow.value = true
    }

  }
};
//删除
const handledelete = (row) => {
  postApi({}, `/mosty-jcgl/plansummary/delPlanSummary/${row.id}`).then(() => {
    ElMessage.success("删除成功");
    getListData();
  });
};
//关闭新增弹窗
const closeAdd = () => {
  addplanShow.value = false;
  wcplanShow.value = false;
  getListData();
};
//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  pageData.pageConfiger.pageSize = currentSize;
  getListData();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  pageData.pageConfiger.pageCurrent = currentPage;
  getListData();
};
</script>

<style lang="scss" scoped>
.dialog-box {
  z-index: 3 !important;
}

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

.el-form {
  width: 100%;
  display: block;
  // flex-wrap: wrap;
}
</style>