<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <seek-page :seekList="seekList" @search="search"></seek-page>

      <el-tabs v-model="tabValue" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="99"></el-tab-pane>
        <el-tab-pane label="草稿" name="0"></el-tab-pane>
        <el-tab-pane label="审核中" name="1"></el-tab-pane>
        <el-tab-pane label="驳回" name="3"></el-tab-pane>
        <el-tab-pane label="办结" name="2"></el-tab-pane>
      </el-tabs>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        row-key="code"
        :selection.sync="selection"
        @sort-change="onSortChange"
        autoAmendPage
        @columns-change="handleColumnChange"
        :cache-key="cacheKeyUrl"
        :pageSize="20"
        :height="tableHeight"
        @fullscreen-change="fullscreenChange"
      >
        <template v-slot:toolbar>
          <el-button type="primary" @click="toAdd()">新增</el-button>
          <el-button type="danger" @click="toDelAll()">批量删除</el-button>
          <!-- <el-button type="success" @click="toEnd()">导出</el-button> -->
          <el-button type="primary" @click="printing()">打印</el-button>
        </template>

        <template v-slot:docNo="{ row }">
          <el-link type="primary" :underline="false" @click="toEdit('detail', row)">
            {{ row.docNo }}
          </el-link>
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }">
            <template v-if="row.approvalStatus == 0 || row.approvalStatus == 3">
              <el-link
                  type="primary"
                  :underline="false"
                  @click="toEdit('edit', row)"
              >
                  编辑
              </el-link>
              <el-link
                  type="primary"
                  :underline="false"
                  @click="toSubmit(row)"
              >
                  提交
              </el-link>
              <el-popconfirm
                class="ele-action"
                title="确定要删除吗？"
                @confirm="
                  toDel(row)
                "
              >
                <template v-slot:reference>
                  <el-link type="danger" :underline="false"> 删除 </el-link>
                </template>
              </el-popconfirm>
              
            </template>
            <el-link
                v-if="row.approvalStatus == 2 && row.status == 1"
                type="primary"
                :underline="false"
                @click="toChangeStatus(row, 2)"
            >
                发布
            </el-link>

            <el-link
                v-if="row.approvalStatus == 2 && row.status == 2"
                type="primary"
                @click="toChangeStatus(row, 3)"
                >作废</el-link
            >
        </template>
      </ele-pro-table>
    </el-card>
    <documentDialog ref="documentDialogRef" @done="handleSelectDone" />
    <process-submit-dialog
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </div>
</template>

<script>
  import processSubmitDialog  from '@/BIZComponents/enventSubmitDialog/processSubmitDialog'
  import documentDialog from './components/documentDialog.vue';
  import tableColumnsMixin from '@/mixins/tableColumnsMixin';
  import { noticeDocumentPageV1API, noticeDocumentDeleteAPI, batchDeleteNotice, noticeStatusChange } from '@/api/documents/noticeIssuance/index.js';
  import {
  listOrganizations
} from '@/api/system/organization';
  
  export default {
    mixins: [tableColumnsMixin],
    components: {
      documentDialog,
      processSubmitDialog
    },

    data() {
      return {
        organizationList: [],
        processSubmitDialogFlag: false,
        tabValue: '99',
        id: '',
        where: {},
        // 加载状态
        loading: false,
        urgencyLevelOp: [
          { label: '普通', value: '1' },
          { label: '紧急', value: '2' },
          { label: '特急', value: '3' }
        ],
        statusOpt: [
          { label: '待发布', value: '1' },
          { label: '已发布', value: '2' },
          { label: '作废', value: '3' }
        ],
        approvalStatusOp: [
          { label: '草稿', value: '0' },
          { label: '审核中', value: '1' },
          { label: '驳回', value: '3' },
          { label: '办结', value: '2' }
        ],
        selection: [],
        cacheKeyUrl: '7cc8e5d2-wt-noticeIssuance-index',
        columnsVersion: 0,
        tableHeight: 'calc(100vh - 375px)',
      };
    },
    computed: {
      // 表格列配置
      seekList() {
        return [
          {
            label: '标题：',
            value: 'title',
            type: 'input',
            placeholder: ''
          },
          {
            label: '发文字号：',
            value: 'docNumber',
            type: 'input',
            placeholder: '',
            labelWidth: 100
          },
          {
            label: '发文机关：',
            value: 'issuingAuthorityId',
            type: 'select',
            labelWidth: 100,
            planList: this.organizationList
          },
          {
            label: '紧急程度：',
            value: 'urgencyLevelId',
            type: 'select',
            width: 240,
            planList: this.urgencyLevelOp

          },
        ];
      },
      columns() {
        const num = this.columnsVersion;
        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            fixed: 'left'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },

          {
            prop: 'docNo',
            slot: 'docNo',
            label: '发文编码',
            align: 'center',
            minWidth: 130,
            showOverflowTooltip: true
          },

          {
            prop: 'title',
            label: '标题',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'docNumber',
            label: '发文字号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'issuingAuthority',
            label: '发文机关',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'draftAuthor',
            label: '拟稿人',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'createTime',
            label: '拟稿日期',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'urgencyLevelId',
            label: '紧急程度',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true,
            formatter: (row) => {
              const obj = this.urgencyLevelOp.find((i) => i.value == row.urgencyLevelId);
              return obj && obj.label;
            }
          },
          {
            prop: 'approvalStatus',
            label: '审批状态',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true,
            formatter: (row) => {
              const obj = this.approvalStatusOp.find((i) => i.value == row.approvalStatus);
              return obj && obj.label;
            }
          },
          {
            prop: 'status',
            label: '发布状态',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              const obj = this.statusOpt.find((i) => i.value == row.status);
              return obj && obj.label;
            }
          },
          {
            prop: 'action',
            label: '操作',
            align: 'center',
            slot: 'action',
            width: 180,
            showOverflowTooltip: true
          }
        ];
      },

      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },
    watch: {
  
    },
    created() {
      this.getOrganizationList();
    },
    mounted() {
      // this.reload();
    },

    methods: {
      // 获取部门列表
    getOrganizationList() {
      listOrganizations()
        .then((list) => {
          let _list = list.filter((i) => i.name != '超级管理员');
          // 转换为树形结构
          this.organizationList = _list.map((i) => ({
            label: i.name,
            value: i.id
          }));
        })
        .catch((e) => {
          console.error('获取部门列表失败:', e);
          this.$message.error('获取部门列表失败');
        });
    },
        toSubmit(res) {
          this.processSubmitDialogFlag = true;
          this.$nextTick(() => {
            let params = {
              businessId: res.id,
              businessKey: 'fm_notice_document_approval',
              formCreateUserId: res.createUserId,
              variables: {
                businessCode: res.docNo,
                businessName: res.title,
                businessType: '通知公文'
              }
            };
            this.$refs.processSubmitDialogRef.init(params);
          });
        },

        toAdd() {
          this.$refs.documentDialogRef.open();
        },
        toEdit(type, row = {}) {
          this.current = row;
          this.$router.push({
            path: '/documents/noticeIssuance/add-or-edit',
            // query
            query: {
              id: this.current.id,
              type: type
            }
          });
        },
        toDel(row) {
          const loading = this.$loading({ lock: true });
          noticeDocumentDeleteAPI(row.id)
            .then((msg) => {
              loading.close();
              this.$message.success('操作成功');
              this.reload();
            })
            .catch((e) => {
              loading.close();
              // this.$message.error(e.message);
            });
        },
        handleSelectDone(list) {
          this.current = list[0];
          this.$router.push({
            path: '/documents/noticeIssuance/add-or-edit',
            // query
            query: {
              id: this.current.id,
              type: 'add'
            }
          });
        },

        toChangeStatus(row, status) {
          noticeStatusChange({id: row.id, status: status})
            .then((msg) => {
              this.$message.success('操作成功');
              this.reload();
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        },

      search(e) {
        this.reload(e);
      },

      handleTabClick() {
        this.reload();
      },

      toDelAll() {
        if (!this.selection.length) {
          return this.$message.warning('请至少选择一条通知！');
        }
        batchDeleteNotice({
          ids: this.selection.map((i) => i.id)
        }).then((res) => {
          if (res) {
            this.$message.success('删除成功');
            this.reload();
          }
        }).catch((err) => {
          this.$message.error(err.message);
        });
      },

      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        console.log(this.tabValue, '888');
    
        let params = {
          ...where,
          ...order,
          approvalStatus: this.tabValue == 99 ? '' : this.tabValue,
          pageNum: page,
          size: limit,
        };

        return noticeDocumentPageV1API({ ...params });
      },

      onSortChange(e) {
        let sort = {
          orderBy: e.order,
          sortName: e.prop
        };
        this.sort = sort;
        this.reload();
      },

      fullscreenChange(fullscreen) {
        if (fullscreen) {
          this.tableHeight = 'calc(100vh - 120px)';
        } else {
          this.tableHeight = 'calc(100vh - 375px)';
        }
      },

      /* 刷新表格 */
      reload(where = {}) {
        this.$nextTick(() => {
          this.$refs.table.reload({ page: 1, where, approvalStatus: this.tabValue == 99 ? '' : this.tabValue });
        });
      },

      printing() {
        // 检查是否有选中的数据
        if (!this.selection || this.selection.length === 0 || this.selection.length > 1) {
          this.$message.warning('请选择一条要打印的数据');
          return;
        }
        
        // 获取第一条选中的数据
        const row = this.selection[0];
        
        if (row.content) {
          // 打开打印窗口
          this.openPrintWindow(row.content);
        } else {
          this.$message.warning('选中的数据没有可打印的内容');
        }
      },
      
      // 打开打印窗口
      openPrintWindow(content) {
        // 创建新窗口
        const printWindow = window.open('', '_blank');
        if (!printWindow) {
          this.$message.error('请允许弹出窗口以进行打印');
          return;
        }
        
        // 构建打印页面的 HTML
        const printHtml = `
          <!DOCTYPE html>
          <html>
          <head>
            <meta charset="utf-8">
            <title>打印</title>
            <style>
              body {
                margin: 0;
                padding: 20px;
                font-family: 'SimSun', '宋体', serif;
                font-size: 16px;
                line-height: 1.8;
              }
              .print-content {
                max-width: 800px;
                margin: 0 auto;
              }
              @media print {
                body {
                  padding: 0;
                }
              }
            </style>
          </head>
          <body>
            <div class="print-content">
              ${content}
            </div>
            <script>
              window.onload = function() {
                setTimeout(function() {
                  window.print();
                }, 500);
              };
            <\/script>
          </body>
          </html>
        `;
        
        // 写入内容并打印
        printWindow.document.write(printHtml);
        printWindow.document.close();
      },
    }
  };
</script>

<style scoped>

</style>
