<template>
  <div>
    <MOSTY.PageTree :pageTitle="'责任书列表'" :searchType="'01'" @getDeptId="getdeptData">
      <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">
            <section class="flex">
              <section class="left-tj">
                <Sjtj :info="countlist" :isShowTip="false" :isShowBottom="false" :width="280" mb="6px" />
              </section>
            </section>
          </section>
        </section>
        <el-divider />
        <section class="query-flex" ref="queryHeight">
          <section class="query-section">
            <section class="flex">
              <MOSTY.DictRidioAndSelect class="ml12" style="width: 250px;" :dictData="filterYear(7, true)"
                v-model="listQuery.year" selectType="select" :disabled="false" />
              <MOSTY.DictRidioAndSelect class="ml12" style="width: 250px;" :dictData="signlist"
                v-model="listQuery.signtype" selectType="select" :placeholder='"请选择签订方式"' :disabled="false" />
              <el-input class="ml12" v-model="listQuery.zrsmc" clearable placeholder="请输入责任书名称"
                style="width: 250px"></el-input>
            </section>
            <template v-if="isOpensearch">
              <el-input class="mt10 ml12" v-model="listQuery.ryxm" clearable placeholder="请输入签订人姓名"
                style="width: 250px"></el-input>
            </template>
          </section>
          <div class="query-btn">
            <div class="toggle" :class="{ active: isOpensearch }" @click="handleClickOpen">
              <span>{{ isOpensearch ? "收起" : "展开" }}筛选</span>
              <el-icon>
                <DArrowLeft />
              </el-icon>
            </div>
            <el-button @click="handleFilter(listQuery)" class="ml6">
              <el-icon>
                <Search />
              </el-icon>
              <span>查询</span></el-button>
            <el-button @click="handleRest">
              <el-icon>
                <Refresh />
              </el-icon><span>重置</span></el-button>
          </div>
        </section>
        <el-divider />
        <div class="button">
          <el-button type="primary" v-if="isAdmin" @click="addwqModel">
            <span>责任书模板配置</span></el-button>
          <!-- <el-button type="primary" @click="addBatchSign">
            <span>批量签订</span></el-button> -->
          <el-button type="primary" @click="addwq">
            <span>网签新增</span></el-button>
          <el-button class='mr10' type="primary" @click="addxx">
            <!-- v-if="addbtnshow" -->
            <span>线下新增</span></el-button>
          <el-button class="dcbtn mr10" v-loading="loadingShow" @click="onloadExcel">导出Excel</el-button>
          <router-link to="/dutyBook/jgryandzz/zrs" class="mr10">
            <el-button type="primary" @click="CloseEvent">
              <el-icon>
                <ArrowLeft />
              </el-icon>
              <span>返回</span>
            </el-button> </router-link>
        </div>
      </template>
      <template #table>
        <section :style="{ 'height': totalHeights }">
          <MOSTY.Table :table-columns="tableColumns" :isSelect="true" :isSort="true" :tableData="tableData"
            actionsW="350" :tableloading="tableloading" element-loading-text="数据加载中...">
            <template #zrslx="{ row }">
              <dict-tag :options="D_TB_ZRSLX" :value="row.zrslx" :tag="false" />
            </template>
            <template #signtype="{ row }">
              <span v-if="row.signtype == '1'">网签</span>
              <span v-else>线下签</span>
            </template>
            <template #groupName="{ row }">
              <span v-if="row.xflx == '1'">{{ row.groupName }}</span>
              <span v-else>{{ row.ryxm }}</span>
            </template>
            <template #qdzt="{ row }">
              <dict-tag :options="D_TB_ZRSQDZT" :value="row.qdzt" :tag="false" />
            </template>
            <template #actions="{ row }">
              <span class="operedit" @click="handlexg(row)"
                v-if="row.signtype == '2' ? true : (row.qdzt == '2' || row.ldspzt == '02')">
                <el-icon>
                  <EditPen />
                </el-icon>修改</span>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要下发?"
                v-if="row.qdzt == '2'" @confirm="showInfo(row)">
                <template #reference>
                  <span class="operesee" size="small"><el-icon>
                      <Position />
                    </el-icon>下发</span>
                </template>
              </el-popconfirm>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                @confirm="handledelete(row)">
                <template #reference>
                  <!-- row.id.substring(0, 4) == USERID.substring(0, 4) && fqbmid rybmid  -->
                  <span v-if="row.fqbmid == ssbmid || row.rybmid == ssbmid || isAqbmOrLdBz" class="operdel"
                    size="small"><el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
              <span class="operedown" @click="registration(row)"><el-icon>
                  <Compass />
                </el-icon>查看</span>
              <span v-if="row.qdzt != '2'" class="operesee" @click="downloadFile(row)"><el-icon>
                  <Download />
                </el-icon>导出</span>
            </template>

          </MOSTY.Table>
        </section>
        <div class="fenye">
          <MOSTY.Pages :pageConfiger="pageConfiger" :pageSizeArr="[15, 20, 50, 100]" @changeNo="handleCurrentChange"
            @changeSize="handleSizeChange" />
        </div>
      </template>
    </MOSTY.PageTree>
    <!-- 网签模板-->
    <div v-if="addDiaModelShow" class="dialog-box">
      <AddWqModel v-if="addDiaModelShow" :title="title" @changeAddVi="changeAddViModel" />
    </div>
    <!-- 网签新增弹出框 -->
    <div v-if="addDiaShow" class="dialog-box">
      <AddWq v-if="addDiaShow" :title="title" :xqId="xqId" :isdisabled='isdisabled' @changeAddVi="changeAddVi"
        :rowdata="seeData" />
    </div>
    <!-- 线下签新增弹出框 -->
    <div v-if="addDiaShowxxq" class="dialog-box">
      <AddXxq v-if="addDiaShowxxq" :title="title" :xqId="xqId" :isdisabled='isdisabled' @changeAddVi="changeAddVi"
        :rowdata="seeData" />
    </div>

    <!-- 责任书查看进度弹窗 -->
    <ShowPlan v-model="showPlanDialog" :title="title" :xqId="xqId" :rowdata="seeData" />
    <!-- 责任书详情弹窗 -->
    <ZrsInfo v-model="showInfoDialog" :xqId="xqId" @close='showInfoDialog = false' />

    <!-- 批量签订 -->
    <div v-if="isShowBatchSignTC" class="dialog-box">
      <BatchSign title="责任书批量签订" @ok="batchSignOk" />
    </div>
  </div>
</template>

<script setup>
// 引入
import { onMounted, ref, defineEmits, reactive, watch, nextTick, getCurrentInstance } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
// import AddWq from "./addWq.vue";
import AddWq from "./addWqOld.vue"; // addWq
import AddWqModel from "./addWqModel.vue";
import AddXxq from "./addXxqOld.vue"; // addXxq
import ShowPlan from "./showPlan.vue";
import ZrsInfo from "./zrsInfo.vue";
import BatchSign from "./zrsListCom/batchSign.vue";
import { filterYear, filterqx } from "@/utils/auth.js";
import { getApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import { exportXlsx, downloadImg } from "@/excel/Export2Excel.js";
import { getItem } from "@/utils/storage";
import { useRouter } from 'vue-router';
import { useStore } from "vuex";
import { getFile } from "@/utils/getFile.js";
import Sjtj from '@/views/dataReportWork/aqjypx/components/sjtj.vue'
import { filter } from "lodash";
const router = useRouter()
const store = useStore();
const { proxy } = getCurrentInstance();
const { D_TB_ZRSLX, D_TB_ZRSQDZT } = proxy.$dict("D_TB_ZRSLX", "D_TB_ZRSQDZT");
// 数据
const tableloading = ref(false);
const isAdmin = getItem("USERID") === '000000';
/**所属部门id */
const ssbmid = getItem("deptId")?.ssbmid + '';
const xqId = ref("");
const isOpen = ref(false);
const addbtnshow = ref(false)
const addDiaShowxxq = ref(false)
const seeData = ref({});
const addDiaShow = ref(false); //新增弹窗
const addDiaModelShow = ref(false); //新增弹窗
const isOpensearch = ref(false)
const showPlanDialog = ref(false); //查看进度弹窗
const showInfoDialog = ref(false); //查看弹窗
const title = ref("网签责任书新增");
const isShowBatchSignTC = ref(false)
/** 是否安全部门,领导班子 */
const isAqbmOrLdBz = ref(filterqx('isaqbm') === '1' || filterqx('isldbz') === '1')
const emits = defineEmits(["close"]);
const tableData = ref([]);
const tableColumns = ref([
  {
    title: "责任书名称",
    prop: "zrsmc",
  },
  {
    title: "责任书类型",
    prop: "zrslx",
    slot: true
  },
  {
    title: "发起单位",
    prop: "fqdwmc",
    slot: false
  },
  {
    title: "发起部门",
    prop: "fqbmmc"
  },
  {
    title: "被签订单位/部门",
    prop: "rybmmc"
  },
  {
    title: "审批人",
    prop: "ldxm"
  },
  {
    title: "下发时间",
    prop: "xtCjsj",
  },
  {
    title: "签订方式",
    prop: "signtype",
    slot: true
  },
  {
    title: "签订人",
    prop: "groupName",
    slot: true
  },
  {
    title: "签订状态",
    prop: "qdzt",
    slot: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const pageConfiger = reactive({
  pageSize: 15,
  pageCurrent: 1,
  total: 0
})
const countlist = ref([
  { title: '网签已签订责任书', num: 0, icon: 'ccss/icon_02.png' },
  { title: '线下签已签订责任书', num: 0, icon: 'ccss/icon_03.png' },
  { title: '已签订状态', num: 0, icon: 'ccss/icon_04.png' },
  { title: '未签订状态', num: 0, icon: 'ccss/icon_05.png' },
])
const isdisabled = ref(false)
const signlist = ref([
  { value: '1', label: '网签' },
  { value: '2', label: '线下签' }
])
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 10,
  fqbmid: "",
  zrsmc: "",
  year: new Date().getFullYear()
});
const totalHeights = ref(null)
const getHeight = ref(null)
const queryHeight = ref(null)
function handleRest() {
  listQuery.year = new Date().getFullYear()
  listQuery.signtype = ''
  listQuery.zrsmc = ''
  listQuery.ryxm = ''
  listQuery.pageCurrent = 1
  pageConfiger.pageCurrent = 1
  getDataList();
  getcount()
}
watch(() => isOpen.value, (val) => {
  nextTick(() => {
    if (val) {
      totalHeights.value = `calc(100vh - ${337 + queryHeight.value.offsetHeight + getHeight.value.offsetHeight}px)`
    } else {
      totalHeights.value = `calc(100vh - 373px)`
    }

  })
}, {
  deep: true,
  immediate: true
})
const handleClickOpen = () => {
  isOpensearch.value = !isOpensearch.value
  nextTick(() => {
    if (isOpensearch.value) {
      totalHeights.value = `calc(100vh - ${337 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
    } else {
      totalHeights.value = `calc(100vh - 373px)`
    }



  })
}
// 初始化
onMounted(() => {
  nextTick(() => {
    totalHeights.value = `calc(100vh - ${337 + getHeight.value.offsetHeight + queryHeight.value.offsetHeight}px)`
  })
});
// 附件下载
async function downloadFile(row) {
  let data = await getFile(row.files)
  fileAjax(data.innerUrl, function (xhr) {
    _downloadFile(xhr.response, data.originalName)
  }, {
    responseType: 'blob'
  })
}
function fileAjax(url, callback, options) {
  let xhr = new XMLHttpRequest()
  xhr.open('get', url, true)
  if (options.responseType) {
    xhr.responseType = options.responseType
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      callback(xhr)
    }
  }
  xhr.send()
}
function _downloadFile(content, filename) {
  window.URL = window.URL || window.webkitURL
  let a = document.createElement('a')
  let blob = new Blob([content])
  // 通过二进制文件创建url
  let url = window.URL.createObjectURL(blob)
  a.href = url
  a.download = filename
  a.click()
  // 销毁创建的url
  window.URL.revokeObjectURL(url)
}
// 查看详情
function showInfo(row) {
  getApi({ id: row.id }, '/mosty-jcgl/zrs/xfZrs').then(res => {
    ElMessage.success("下发成功");
    getDataList();
    getcount()
  })
}
//查询
function handleFilter() {
  getDataList();
  getcount()
}
//获取默认部门
const getdeptData = (val) => {
  //只有本单位或本部门才能够新增
  if (getItem('deptId').ssdwid == val.id || getItem('deptId').ssbmid == val.id || getItem('deptId').ssdwid + 'XN' == val.id) {
    addbtnshow.value = true
  } else {
    addbtnshow.value = false
  }
  listQuery.fqbmid = val.id;
  listQuery.pageCurrent = 1
  pageConfiger.pageCurrent = 1
  getDataList();
  getcount()
}


//责任书列表中的签订情况统计接口
function getcount() {
  let params = {
    year: listQuery.year,
    ssbmid: listQuery.fqbmid,
  }
  getApi(params, '/mosty-jcgl/zrs/getZrsStatistics').then(res => {
    if (res) {
      countlist.value[0].num = res.wq
      countlist.value[1].num = res.xxq
      countlist.value[2].num = res.yqd
      countlist.value[3].num = res.wqd
    }
  })
}
//获取列表数据
function getDataList() {
  tableloading.value = true;
  getApi(listQuery, "/mosty-jcgl/zrs/getPageList").then((res) => {
    if (res.records) {
      tableloading.value = false;
      tableData.value = res.records;
      pageConfiger.total = res.total;
    }
  }).catch(() => {
    tableData.value = [];
    tableloading.value = false;
  });
}
/** 批量签订 */
const addBatchSign = () => {
  isShowBatchSignTC.value = true
}
//网签新增
function addwqModel() {
  tableloading.value = false;
  seeData.value = {};
  title.value = "责任书模板新增";
  addDiaModelShow.value = true;
}
//网签新增
function addwq() {
  tableloading.value = false;
  seeData.value = {};
  title.value = "网签责任书新增";
  addDiaShow.value = true;
}
//线下签新增
function addxx() {
  tableloading.value = false;
  seeData.value = {};
  title.value = "线下签订责任书新增";
  addDiaShowxxq.value = true;
}
//修改
function handlexg(row) {
  if (row.signtype == '1') {
    xqId.value = row.id;
    title.value = "网签责任书修改";
    addDiaShow.value = true;
  } else {
    xqId.value = row.id;
    title.value = "线下签订责任书修改";
    addDiaShowxxq.value = true;
  }
}
const registration = (row) => {
  if (row.signtype == '1') {
    xqId.value = row.id;
    title.value = "网签责任书查看";
    addDiaShow.value = true;
    isdisabled.value = true
  } else {
    xqId.value = row.id;
    title.value = "线下签订责任书查看";
    addDiaShowxxq.value = true;
    isdisabled.value = true
  }
};
const changeAddViModel = () => {
  addDiaModelShow.value = false;
  getDataList();
  getcount()
}
// 控制新增弹出框的展示
const changeAddVi = (val) => {
  xqId.value = null
  addDiaShow.value = false;
  addDiaShowxxq.value = false;
  isdisabled.value = false
  getDataList();
  getcount()
};
// 批量新增ok
const batchSignOk = (val) => {
  // xqId.value = null
  // addDiaShow.value = false;
  // addDiaShowxxq.value = false;
  // isdisabled.value = false
  isShowBatchSignTC.value = false
  getDataList();
  getcount()
};

//删除
function handledelete(row) {
  getApi({ id: row.id }, `/mosty-jcgl/zrs/delZrsOne`).then((res) => {
    ElMessage.success("删除成功");
    getDataList();
    getcount()
  });
}
const loadingShow = ref(false)
//导出Excel
function onloadExcel() {
  let title = {
    zrsmc: "责任书名称",
    zrslxmc: "责任书类型",
    fqdwmc: "发起单位",
    fqbmmc: "发起部门",
    rydwmc: "被签订单位/部门",
    ldxm: "审批人",
    xtCjsj: "下发时间",
    signtypemc: "签订方式",
    ryxm: "签订人",
    qdztmc: "签订状态"
  };
  const params = {
    pageCurrent: 1,
    pageSize: 10000,
    fqbmid: listQuery.fqbmid,
    year: listQuery.year
  }
  loadingShow.value = true
  getApi(params, "/mosty-jcgl/zrs/getPageList").then((res) => {
    if (res.records) {
      let data = res.records;
      if (data) {
        for (let i = 0; i < data.length; i++) {
          data[i].zrslxmc = proxy.$getDictVal(data[i].zrslx, D_TB_ZRSLX);
          data[i].signtypemc = data[i].signtype == "1" ? "网签" : "线下签";
          data[i].qdztmc = proxy.$getDictVal(data[i].qdzt, D_TB_ZRSQDZT);
        }
        let tablename = "责任书.xlsx";
        exportXlsx(title, data, '责任书', tablename);
        loadingShow.value = false
      }
    }
  }).catch(() => {
    loadingShow.value = false
  });
}


//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getDataList();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getDataList();
};
function CloseEvent() {
  let arr = store.getters.tagsViewList;
  for (let i = 0; i < arr.length; i++) {
    const e = arr[i];
    if (e.path == '/jgryandzz/zrsstatisticsList') {
      arr.splice(i, 1);
    }
  }
  router.push("/dutyBook/jgryandzz/zrs");
}
</script>

<style lang="scss" scoped>
.lable-bq {
  font-size: 25px;
}

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

.bigBox {
  display: flex;

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



  .right {
    padding: 0 10px;
    margin: 10px;

  }
}
</style>
