﻿﻿﻿﻿﻿﻿<template>
  <a-layout>
    <div class="page" v-if="currentPage=='plan'">
      <a-layout-header style="background:#fff">
        <a-form layout="inline" class="demo-form-inline">
          <a-form-item label="全覆盖督查名称" style="min-width: 19%;">
            <a-input v-model:value="name" placeholder="全覆盖督查名称" allow-clear />
          </a-form-item>
          <a-form-item label="督查年度" style="min-width: 19%;">
            <a-date-picker
              v-model:value="isYear"
              :open="isOpenYear"
              @change="onChange"
              @panelChange="panelYearChange"
              @openChange="handYearChange"
              format="YYYY"
              mode="year"
              allow-clear
              placeholder="调度年份" />
          </a-form-item>
          <a-form-item>
            <a-button @click="searchPlan" type="primary" >查询</a-button>
          </a-form-item>
          <a-form-item>
            <a-button @click="addPlanDialog" type="primary"  v-if="isShow && readOnlyRole == 'display'">添加计划</a-button>
          </a-form-item>
        </a-form>
      </a-layout-header>
      <a-layout-content class="main-container">
        <a-table
          :columns="columns"
          :data-source="tableData"
          row-key="id"
          style="width: 100%;"
          :style="{ height: tableHeight + 'px' }"
          :scroll="{ x: true, y: tableHeight - 60}"
          :pagination="false"
          bordered
          ref="planTask">
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex === 'index'">
              <span>{{ (pageIndex - 1) * pageSize + (index + 1) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'isStatrt'">
              <span v-if="record.isStatrt=='0'" style="font-size: 12px">未下发</span>
              <span v-if="record.isStatrt=='1'" style="font-size: 12px">已下发</span>
            </template>
            <template v-else-if="column.dataIndex === 'sendTm'">
              {{ formatDate(record.sendTm) }}
            </template>
            <template v-else-if="column.dataIndex === 'intm'">
              {{ formatDate(record.intm) }}
            </template>
            <template v-else-if="column.dataIndex === 'uptm'">
              {{ formatDate(record.uptm) }}
            </template>
            <template v-else-if="column.dataIndex === 'createOrg'">
              {{ record.createOrg }}
            </template>
            <template v-else-if="column.dataIndex === 'action'">
              <template v-if="readOnlyRole == 'display'">
                <a-button type="danger" size="small" v-if="record.isStatrt=='0'" :disabled="disabled1" @click="nextStep(record.id)">下发</a-button>
                <a-button type="primary" size="small" @click="editRow(record)">编辑</a-button>
                <a-button type="danger" size="small" v-if="record.isStatrt=='0'" @click="deleteRow(record.id)">删除</a-button>
                <a-button type="danger" size="small" v-if="record.isStatrt=='1'" @click="refreshData(record.id)" title="更新自查数据">刷新</a-button>
              </template>
            </template>
          </template>
        </a-table>
        <a-pagination
          show-size-changer
          :pageSize="pageSize" @update:pageSize="pageSize = $event"
          :total="total"
          :page-size-options="['10', '20', '30', '40']"
          :show-total="total => `共${total}条`"
          @showSizeChange="handleSizeChange"
          @change="handleCurrentChange"
          style="margin-top: 10px;" />
      </a-layout-content>
      <a-modal :title="dialogTitle +'全覆盖督查计划'" :open="addDialogVisible" width="600px" @cancel="addDialogVisible=false">
        <a-form :model="addObj" :label-col="{span: 8}" :wrapper-col="{span: 16}" :rules="rule" ref="form">
          <a-form-item label="全覆盖督查名称" prop="name">
            <a-input v-model:value="addObj.name" placeholder="全覆盖督查名称" allow-clear />
          </a-form-item>
          <a-form-item v-if="flag" label="督查年度" prop="year">
            <a-date-picker
              v-model:value="isAddYear"
              :open="isOpenAddYear"
              @change="onAddChange"
              @panelChange="panelAddYearChange"
              @openChange="handAddYearChange"
              format="YYYY"
              mode="year"
              allow-clear
              placeholder="调度年份"
              :disabled="addObj.isStatrt=='1'" />
          </a-form-item>
          <a-form-item v-if="flag" label="时效(月)" prop="validityPeriod">
            <a-input v-model:value="addObj.validityPeriod" placeholder="全覆盖督查名称" :disabled="addObj.isStatrt=='1'" allow-clear />
          </a-form-item>
          <a-form-item label="督查事项" prop="dictTypes">
            <a-select v-if="flag" v-model:value="addObj.dictTypes" placeholder="请选择" mode="tags" :disabled="addObj.isStatrt=='1'">
              <a-select-option v-for="(system,index) in supervisionListAdd" :key="index" :value="system.dictTypeNum" :disabled="system.optionalStatus == '1'">{{ system.nm }}</a-select-option>
            </a-select>
            <a-select v-else v-model:value="addObj.dictTypes" placeholder="请选择" :disabled="addObj.isStatrt == '1'">
              <a-select-option v-for="(system, index) in supervisionListAdd" :key="index" :value="system.dictTypeNum" :disabled="system.optionalStatus == '1'">{{ system.nm }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="展示页面" prop="displayPage">
            <a-select v-model:value="addObj.displayPage" placeholder="请选择" mode="tags">
              <a-select-option v-for="(system,index) in displayPageList" :key="index" :value="system.key">{{ system.val }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 16, offset: 8 }" prop="planType">
            <a-switch v-model="addObj.planType" checked-children="开" un-checked-children="关" @change="checkChange" :disabled="dialogTitle == '编辑'" />全覆盖督查常设事项
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 16, offset: 8 }">
            <a-upload
              v-if="isAutoUpload"
              :action="`/modular-source/6ace62b8e2bb467d98286d260aebcef2/pdcApi/file/insert?bizId=${this.bizId}`"
              :accept="'.pdf,.PDF'"
              :headers="header"
              @change="handleChange"
              :show-upload-list="false"
            >
              <a-button type="primary" :disabled="addObj.isStatrt=='1'">点击上传</a-button><span>只能上传pdf</span>
            </a-upload>
            <a-upload
              v-if="!isAutoUpload"
              :accept="'.pdf,.PDF'"
              :headers="header"
              :file-list="addFileList"
              :remove="handleRemove"
              :before-upload="beforeUpload"
            >
              <a-button type="primary" :disabled="addObj.isStatrt=='1'">点击上传</a-button><span>只能上传pdf</span>
            </a-upload>
          </a-form-item>
          <div style="width:100%;height:120px;overflow:auto;" v-if="isAutoUpload">
            <a-table
              :columns="uploadColumns"
              :data-source="fileList"
              row-key="id"
              style="width: 100%;"
              :pagination="false"
              bordered>
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'action'">
                  <span><a :href="'/pdcApi' + record.filePath" download style="color:#66b1ff">下载</a></span>&nbsp;&nbsp;
                  <span style="color:palevioletred" @click="removeFile(record.id)" v-if="addObj.isStatrt!='1'">删除</span>
                </template>
              </template>
            </a-table>
          </div>
        </a-form>
        <div slot="footer" class="dialog-footer" style="text-align: center">
          <a-button @click="addDialogVisible = false" size="small">取 消</a-button>
          <a-button type="primary" size="small" @click="addPlanOk" v-if="isShow">确 定</a-button>
        </div>
      </a-modal>
    </div>
  </a-layout>
</template>

<script>
import moment from 'moment';
import { deleteFileById } from '../../api/duChaAPI';
import {
  getDisplayPage,
  getPersPlanType,
  getPersPlanTypeNew,
} from '../../api/duChaPlan.js';
import request from '../../utils/gw_ajax_request.js';
import { dateFormat } from '../../utils/gw_date.js';
export default {
  data() {
    return {
      moment,
      tableHeight: window.innerHeight - 220,
      activeName: 'jdtj',
      activeCode: '',
      loading1: false,
      loading2: false,
      nm: '',
      state: '',
      rule: {
        name: [
          { required: true, message: '请输入督查事项名称', trigger: 'blur' },
        ],
        dictTypes: [
          { required: true, message: '请选择督查事项', trigger: 'blur' },
        ],
        year: [{ required: true, message: '请选择年度', trigger: 'change' }],
        validityPeriod: [
          { required: true, message: '请输入时效', trigger: 'blur' },
          {
            required: true,
            pattern: /^[1-9]\d*$/,
            message: '请输入大于0的正整数',
            trigger: 'blur',
          },
        ],
        finishTm: [
          { required: true, message: '请选择完成时间', trigger: 'blur' },
        ],
        dutyDept: [
          { required: true, message: '请输入责任处室(单位)', trigger: 'blur' },
        ],
        displayPage: [
          { required: true, message: '请选择展示页面', trigger: 'change' },
        ],
      },
      header: {
        persId: localStorage.getItem('persId'),
        accessToken: localStorage.getItem('accessToken'),
      },
      loading: false,
      supervisionList: [],
      supervisionListAdd: [],
      currentPage: 'plan',
      processData: {},
      bizId: '',
      isAutoUpload: false,
      isShowFile: false,
      fileList: [],
      fileCount: 0,
      objType: '',
      name: '',
      isOpenYear: false,
      isYear: null,
      year: null,
      pageIndex: 1,
      pageIndex1: 1,
      total: 0,
      total1: 0,
      pageSize: 10,
      pageSize1: 10,
      addDialogVisible: false,
      formLabelWidth: 80,
      addObj: {},
      dialogTitle: '添加',
      tableData: [],
      tableData_sum: [],
      tableData_sum1: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 50,
          align: 'center',
        },
        {
          title: '全覆盖督查名称',
          dataIndex: 'name',
          width: 240,
          ellipsis: true,
        },
        {
          title: '督查事项',
          dataIndex: 'objName',
          width: 160,
          ellipsis: true,
        },
        {
          title: '督查年度',
          dataIndex: 'year',
          width: 100,
          ellipsis: true,
        },
        {
          title: '时效(月)',
          dataIndex: 'validityPeriod',
          width: 100,
          ellipsis: true,
        },
        {
          title: '下发状态',
          dataIndex: 'isStatrt',
          width: 100,
          ellipsis: true,
        },
        {
          title: '下发时间',
          dataIndex: 'sendTm',
          width: 160,
          ellipsis: true,
        },
        {
          title: '创建人',
          dataIndex: 'persName',
          width: 120,
          ellipsis: true,
        },
        {
          title: '创建时间',
          dataIndex: 'intm',
          width: 160,
          ellipsis: true,
        },
        {
          title: '更新时间',
          dataIndex: 'uptm',
          width: 160,
          ellipsis: true,
        },
        {
          title: '创建机构',
          dataIndex: 'createOrg',
          width: 120,
          ellipsis: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 350,
          ellipsis: true,
        },
      ],
      isOpenAddYear: false,
      isAddYear: null,
      uploadColumns: [
        {
          title: '文件名',
          dataIndex: 'fileName',
          width: 100,
          ellipsis: true,
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          align: 'center',
        },
      ],
      addFileList: [],
      disabled1: false,
      flag: true,
      displayPageList: [],
      readOnlyRole: localStorage.getItem('readOnlyRole'),
    };
  },
  computed: {
    userId: () =>
      localStorage.getItem('persId')
        ? localStorage.getItem('persId')
        : '1098101939614724096',
    isShow: () => {
      if (localStorage.getItem('currentOrgId') == '015') {
        return true;
      }
      return false;
    },
  },
  created() {
    this.getSupervisionList();
    this.getDisplayPage();
  },
  mounted() {
    this.searchPlan();
  },
  methods: {
    onChange(value) {
      console.log(value, 'xxxxx');
      if (value == null) {
        this.year = null;
      }
      this.isOpenYear = false;
      this.isYear = null;
    },
    handYearChange(open) {
      if (open) {
        this.isOpenYear = true;
      } else {
        this.isOpenYear = false;
      }
    },
    panelYearChange(value) {
      this.isYear = value;
      this.year = moment(value).format('YYYY');
      this.isOpenYear = false;
    },
    onAddChange(value) {
      this.isOpenAddYear = false;
      this.isAddYear = null;
    },
    handAddYearChange(open) {
      if (open) {
        this.isOpenAddYear = true;
      } else {
        this.isOpenAddYear = false;
      }
    },
    panelAddYearChange(value) {
      this.isAddYear = value;
      this.addObj.year = moment(value).format('YYYY');
      this.isOpenAddYear = false;
      this.getSupervisionList();
    },
    nextStep(id) {
      this.$message.info('正在下发中...,请稍后');
      this.disabled1 = true;
      request.get('/bis/insp/all/plan/execute/newExecute/' + id).then((res) => {
        if (res.success) {
          this.$message.success('下发成功');
          this.disabled1 = false;
          this.searchPlan();
        } else {
          this.$message.error('下发失败');
        }
      });
    },
    formatDate(text) {
      if (text) {
        return dateFormat(text, 'yyyy-MM-dd');
      }
    },
    deleteRow(id) {
      this.$confirm({
        title: '提示',
        content: '此操作将计划从列表中删除，确认删除该计划吗？',
        okType: 'warning',
        onOk: () => {
          request.post(`/bis/insp/all/plan/delete/${id}`).then((res) => {
            if (res.success) {
              this.searchPlan();
              this.$message.success('删除成功');
            } else {
              this.$message.error(res.message);
            }
          });
        },
      });
    },
    searchPlan() {
      this.loading = true;
      var searchObj = {
        objType: this.objType,
        name: this.name,
        year: this.year,
        pageNum: this.pageIndex,
        pageSize: this.pageSize,
      };
      request.post('/bis/insp/all/plan/list', searchObj).then((res) => {
        if (res.success) {
          res.data.list.forEach((item, index) => {
            item.uptm = item.uptm ? item.uptm : item.intm;
            item.createOrg = '监督处';
          });
          this.tableData = res.data.list;
          this.total = res.data.total;
          this.loading = false;
          // _self.$nextTick(() => {
          //   _self.$refs.planTask.doLayout()
          // })
        } else {
          this.$message.error(res.message);
        }
      });
    },
    getSupervisionList() {
      this.supervisionList = [];
      this.supervisionListAdd = [];
      const params = {
        type: 'other',
        displayStat: '0',
        year: this.addObj.year,
      };
      getPersPlanTypeNew(params)
        .then((res) => {
          if (res.success && res.data.length) {
            // _self.supervisionList = res.data
            this.supervisionListAdd = res.data;
            // _self.supervisionList.push({
            //   name: '全部',
            //   id: ''
            // })
          }
        })
        .catch(() => {
          this.$message.warning('系统异常');
        });
    },
    getDisplayPage() {
      getDisplayPage()
        .then((res) => {
          if (res.success) {
            this.displayPageList = res.data;
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          this.$message.warning('系统异常');
        });
    },
    removeFile(id) {
      this.$confirm({
        title: '提示',
        content: '此操作将永久删除该文件, 是否继续?',
        okType: 'warning',
        onOk: () => {
          deleteFileById(id, this.userId).then((res) => {
            if (res.success) {
              this.getFileList();
            } else {
              this.$message.error(res.message);
            }
          });
        },
      });
    },
    editRow(row) {
      this.bizId = row.id;
      this.addDialogVisible = true;
      this.isAutoUpload = true;
      this.isShowFile = false;
      this.addObj = row;
      this.dialogTitle = '编辑';
      this.isAddYear = row.year ? moment(row.year, 'YYYY') : '';
      this.addObj.year = row.year ? row.year.toString() : '';
      this.addObj.planType = row.planType == '1';
      this.addObj.dictTypes = row.dictTypes
        ? String(row.dictTypes).split(',')
        : [];
      this.addObj.displayPage = row.displayPage
        ? row.displayPage.split(',')
        : [];
      this.flag = row.planType != '1';
      this.getFileList();
    },
    getFileList() {
      const params = {
        bizId: this.bizId,
      };
      request.post(`/file/findPageInfo`, params).then((res) => {
        if (res.success) {
          this.fileList = res.data.list;
        }
      });
    },
    addPlanDialog() {
      this.getSupervisionList();
      this.addDialogVisible = true;
      this.flag = true;
      this.isAutoUpload = false;
      this.isShowFile = true;
      this.bizId = '';
      this.addObj = {};
      this.dialogTitle = '添加';
      this.isAddYear = null;
      this.addObj.year = null;
    },
    addPlanOk() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const dictTypes = this.addObj.planType
            ? this.addObj.dictTypes
            : this.addObj.dictTypes.join(',');
          const arr = [];
          let arr1 = '';
          if (this.addObj.planType) {
            this.supervisionListAdd.forEach((item) => {
              if (item.dictTypeNum == this.addObj.dictTypes) {
                arr1 = item.nm;
              }
            });
          } else {
            this.supervisionListAdd.forEach((item) => {
              this.addObj.dictTypes.forEach((item2) => {
                if (item.dictTypeNum == item2) {
                  arr.push(item.nm);
                }
              });
            });
          }

          const params = {
            name: this.addObj.name,
            validityPeriod: this.addObj.validityPeriod,
            objType: '111',
            dictTypes,
            objName: this.addObj.planType ? arr1 : arr.join(','),
            year: this.addObj.year,
            planType: this.addObj.planType ? '1' : '0',
            displayPage: this.addObj.displayPage.join(','),
          };
          if (this.dialogTitle == '编辑') {
            params.id = this.bizId;
          }
          request.post(`/bis/insp/all/plan`, params).then((res) => {
            if (res.success) {
              this.bizId = res.data.id;
              this.addObj = {};
              this.addDialogVisible = false;

              if (this.addFileList.length > 0 && !this.isAutoUpload) {
                this.$nextTick(() => {
                  this.handleUpload();
                });
              } else {
                this.searchPlan();
              }
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    handleSizeChange(size, val) {
      this.pageSize = val;
      this.searchPlan();
    },
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.searchPlan();
    },
    handleChange(info) {
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.$message.success(`${info.file.name} 导入成功!`);
          this.getFileList();
          this.searchPlan();
        } else {
          this.$message.error(info.file.response.message);
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 导入失败!`);
      }
    },
    handleRemove(file) {
      const index = this.addFileList.indexOf(file);
      const newFileList = this.addFileList.slice();
      newFileList.splice(index, 1);
      this.addFileList = newFileList;
    },
    beforeUpload(file) {
      this.addFileList = [...this.addFileList, file];
      return false;
    },
    handleUpload() {
      const { addFileList } = this;
      addFileList.forEach((file) => {
        const formData = new FormData();
        formData.append('file', file);
        request
          .post(`/file/insert?bizId=${this.bizId}`, formData)
          .then((res) => {
            if (res.success) {
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(() => {
            this.$message.error('上传文件失败!');
          });
      });
      this.searchPlan();
    },
    refreshData(id) {
      request.get('/bis/insp/all/plan/execute/newRefresh/' + id).then((res) => {
        if (res.success) {
          this.$message.success('刷新成功');
        } else {
          this.$message.error('刷新失败');
        }
      });
    },
    checkChange(e) {
      this.flag = !e;
    },
  },
};
</script>

<style lang='less' scoped>
/deep/ .ant-layout-sider,
/deep/ .ant-layout-header,
/deep/ .ant-layout-content {
  background: #fff;
}
.el-container {
  height: 100%;
  display: block;
}

.main-container .el-table {
  height: calc(100% - 40px);
}

.main-container /deep/ .el-table__body-wrapper {
  height: calc(100% - 40px);
  overflow: auto;
}

.demo-form-inline {
  padding-top: 10px;
}

.main-container {
  height: calc(100% - 60px);
}

.item-width {
  width: 70%;
}

.upload-demo {
  display: flex;
}

.el-upload__tip {
  margin-top: 0px;
}

.page {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.leftTree {
  width: 300px;
  height: calc(100% - 20px);
  margin-top: 10px;
  margin-left: 10px;
  box-shadow: 0 1px 6px 0 rgb(32 33 36 / 28%);
}

.rightContent {
  width: calc(100% - 330px);
  height: calc(100% - 20px);
  margin-top: 10px;
  margin-left: 10px;
  box-shadow: 0 1px 6px 0 rgb(32 33 36 / 28%);
}

.backPlan {
  display: block;
  line-height: 30px;
  font-size: 18px;
  font-weight: bold;
  padding: 5px;
  border-bottom: 1px solid #dedede;
  text-indent: 30px;
}

.el-icon-back {
  float: left;
  line-height: 30px;
  font-size: 25px;
  font-weight: bold;
  cursor: pointer;
}

.el-icon-back:hover {
  color: #5bb7e7;
}

.provTree {
  display: block;
  height: calc(100% - 51px);
  padding: 5px;
  overflow: auto;
}

.rightContent /deep/ .el-tabs--border-card {
  width: 100%;
  height: 100%;
  border: 0;
}

.rightContent /deep/ .el-tabs__content {
  height: calc(100% - 70px);
}

.rightContent /deep/ .el-tab-pane {
  height: 100%;
}

.tabs_detail1 .el-table {
  height: 100% !important;
}

.tabs_detail1 /deep/ .el-table__body-wrapper {
  height: calc(100% - 40px);
  overflow: auto;
}

.tabs_detail2 .el-table {
  height: calc(100% - 80px) !important;
}

.tabs_detail2 /deep/.el-table__body-wrapper {
  height: calc(100% - 40px);
  overflow: auto;
}

/deep/ .ant-table-scroll {
  position: relative;
  z-index: 1;
}

/deep/.ant-table-fixed-left,
/deep/ .ant-table-fixed-right {
  z-index: 2;
}
</style>
