<template>
  <a-layout style="padding: 25px;max-height: 500px;background-color: #fff;display: block">
    <p style="text-align: right;" v-if="isShow">
      <a-button type="primary" @click="showAddDialog">新增</a-button>
    </p>
    <a-timeline>
      <a-timeline-item v-for="(activity, index) in activities" :key="index">
        <!-- <p :class="{'is-stat' : activity.stat == '2'}">{{ activity.content }}
          <a-button v-if="activity.isButton && (activity.stat == null || activity.stat == '0' || activity.stat == '3')" @click="handleAppeal(activity.id, activity.stat)" type="primary" ghost style="margin-left: 10px;">我要申诉</a-button>
          <a-button @click="appealRecord(activity.id)" type="primary" ghost style="margin-left: 10px;">申诉记录</a-button>
        </p> -->
        <p style="text-align: left;padding-left: 20px;">
          <span :class="{'is-stat' : activity.stat == '2'}">{{ activity.timestamp }}</span>
          &nbsp;&nbsp;&nbsp;
          <span
            v-if="activity.icon!='ellipsis' && isShow"
            style="color:dodgerblue;cursor:pointer;"
            @click="showFlowDialog(activity)">编辑</span>
          <span
            v-if="activity.icon!='ellipsis' && isShow"
            style="color:palevioletred;cursor:pointer;"
            @click="deleteRecord(activity.id)">删除</span>
        </p>
      </a-timeline-item>
    </a-timeline>
    <a-modal title="编辑流程" v-model="isMoreThanflow" @ok="submitMoreThan" @cancel="isMoreThanflow = false" width="500px">
      <a-form :model="moreThanFlowObj" :label-col="{span: 6}" :wrapper-col="{span: 18}">
        <a-form-item label="流程时间">
          <a-date-picker v-model:value="moreThanFlowObj.intm" placeholder="流程时间" format="YYYY-MM-DD hh:mm:ss" show-time style="width: 90%;" />
        </a-form-item>
        <a-form-item label="流程说明">
          <a-input v-model:value="moreThanFlowObj.zgNotes" autocomplete="off" placeholder="流程说明" style="width:90%;" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 超期申诉弹窗 -->
    <a-modal
      title="超期整改申诉"
      v-model="showAppeal"
      @ok="submitAppeal"
      @cancel="showAppeal = false"
      width="50%"
      :confirm-loading="confirmLoading">
      <a-form :model="appealForm" ref="appealRef" :label-col="{span: 6}" :wrapper-col="{span: 18}" :rules="rules">
        <a-form-item label="申诉说明" prop="appealContent">
          <a-input v-model:value="appealForm.appealContent" type="textarea" autocomplete="off" placeholder="申诉说明" allow-clear/>
        </a-form-item>
        <a-form-item label="申诉附件">
          <a-upload-dragger
            name="file"
            :multiple="true"
            :file-list="fileList"
            :action="appealUrl"
            :show-upload-list="true"
            @change="handleChange"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="plus-square" />
            </p>
            <p>把文件拖入指定区域，完成上传，同样支持点击上传。</p>
          </a-upload-dragger>
        </a-form-item>
        <a-form-item label="附件">
          <a-table
              bordered
              :data-source="fileArray"
              :columns="columns4"
              style="width: 100%;margin: 0 auto;">
                <span slot="action" slot-scope="text, record, index">
                  <a-button size="small" @click="removeFile(text.id, index)" type="danger">删除</a-button>
                  <a-button size="small" @click="downloadFile(text.id,text.fileName)">下载</a-button>
                </span>
          </a-table>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 申诉记录 -->
    <a-modal
      title="申诉记录"
      v-model="showAppealRecord"
      @cancel="showAppealRecord = false"
      :footer="null"
      width="50%">
      <div style="max-height: 500px;">
        <a-row>
          <a-col :span="12" style="height: 500px; overflow: auto;padding: 10px;">
            <a-timeline v-if="appealRecordLine.length">
              <a-timeline-item v-for="(item, index) in appealRecordLine" :key="index" :color="item.color">
                <a-icon slot="dot" :type="item.type" :style="{color: item.color}" style="font-size: 16px;" />
                <p>{{ item.timestamp }}</p>
                <a-card style="position: relative">
                  <h5>{{ item.workflowStatName }}</h5>
                  <p style="font-size: 12px;padding-top: 5px;">{{ item.content }}</p>
                </a-card>
              </a-timeline-item>
            </a-timeline>
            <a-timeline v-else>
              暂无申诉记录
            </a-timeline>
          </a-col>
          <a-col v-if="appealRecordLine.length" :span="12" style="height: 500px; overflow: auto;padding: 10px;">
            <a-form :label-col="{span: 6}" :wrapper-col="{span: 18}">
              <a-form-item label="申诉说明">
                <p>{{ appealContent }}</p>
              </a-form-item>
              <a-form-item v-if="gwComFiles.length" label="申诉附件">
                <div v-for="item in gwComFiles" :key="item.id">
                  <a @click="downloadFile(item.id, item.fileName)">{{ item.fileName }}</a>
                </div>
              </a-form-item>
              <a-form-item v-else label="申诉附件">
                暂无申诉附件
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
      </div>
      <span slot="footer">
        <a-button @click="showAppealRecord = false">关闭</a-button>
      </span>
    </a-modal>
  </a-layout>
</template>

<script>
import moment from 'moment';
import { deleteFileById } from '@/api/duChaAPI';
import request from '../../../utils/gw_ajax_request';
import { formatDateTime, formatDateTime2 } from '../../../utils/gw_date';
import {
  formatWorkflowStat,
  requestPblmProcInstHistory,
  requestPblmProcInstHistoryOver,
} from '../Common/rectify_api';

export default {
  name: 'PblmRectifyTimeLine',
  props: ['pblmId', 'pType', 'pblmCurrentWorkflowStat'],
  data() {
    return {
      isFinish: ['28', '2208', '2103'],
      ProcInstHistory: [],
      activities: [],
      isMoreThanflow: false,
      moreThanFlowObj: {
        id: '',
        intm: '',
        zgNotes: '',
      },
      moment,
      showAppeal: false,
      confirmLoading: false,
      appealForm: {
        appealContent: '',
      },
      bizId: '',
      rules: {
        appealContent: [
          { required: true, message: '申诉说明不能为空', trigger: 'change' },
        ],
      },
      appealRecordData: null,
      showAppealRecord: false,
      appealRecordLine: [],
      appealContent: '',
      gwComFiles: [],
      fileList: [],
      fileArray: [],
      currentId: '',
      columns4: [
        {
          title: '文件名',
          dataIndex: 'fileName',
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
        },
      ],
    };
  },
  created() {
    this.getPblmProcInstHistoryOver();
  },
  computed: {
    formatDateTime() {
      return formatDateTime2;
    },
    formatWorkflowStat() {
      return formatWorkflowStat;
    },
    isShow() {
      return (
        localStorage.getItem('persId') == 'ff2d65f546b84447b7501523cc460df0'
      );
    },
    appealUrl() {
      return process.env.NODE_ENV === 'development'
        ? `/pdcApi/file/insert?bizId=${this.bizId}&bizType=2`
        : `/modular-source/6ace62b8e2bb467d98286d260aebcef2/pdcApi/file/insert?bizId=${this.bizId}&bizType=2`;
    },
  },
  methods: {
    showAddDialog() {
      this.isMoreThanflow = true;
      this.moreThanFlowObj = {};
      this.moreThanFlowObj.pblmId = this.pblmId;
    },
    deleteRecord(id) {
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？, 是否继续?',
        okType: 'warning',
        onOk: () => {
          request
            .post(`/bis/insp/BisInspZgPblmRecord/delete/${id}`)
            .then((res) => {
              if (res.success) {
                this.activities = [];
                this.getPblmProcInstHistoryOver();
              } else {
                this.$message.warning(res.message);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        },
        onCancel: () => {
          this.$message.info('已取消');
        },
      });
    },
    submitMoreThan() {
      this.$confirm({
        title: '提示',
        content: '确认要提交吗？, 是否继续?',
        okType: 'warning',
        onOk: () => {
          var url = this.moreThanFlowObj.id
            ? '/bis/insp/BisInspZgPblmRecord/update'
            : '/bis/insp/BisInspZgPblmRecord/';
          // request.post(`/bis/insp/BisInspZgPblmRecord/update`, this.moreThanFlowObj)
          request
            .post(url, this.moreThanFlowObj)
            .then((res) => {
              if (res.success) {
                this.activities = [];
                this.getPblmProcInstHistoryOver();
                this.isMoreThanflow = false;
              } else {
                this.$message.warning(res.message);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        },
        onCancel: () => {
          this.$message.info('已取消');
        },
      });
    },
    showFlowDialog(item) {
      this.isMoreThanflow = true;
      this.moreThanFlowObj = {
        id: item.id,
        intm: moment(item.intm),
        zgNotes: item.zgNotes,
      };
    },
    getPblmProcInstHistoryOver() {
      this.activities = [];
      requestPblmProcInstHistoryOver(this.pblmId).then((res) => {
        this.loading = false;
        if (res.data && res.data.length > 0) {
          res.data.forEach((item) => {
            this.activities.push({
              id: item.id,
              intm: item.intm,
              zgNotes: item.zgNotes,
              timestamp: formatDateTime2(item.intm),
              size: 'large',
              type: 'primary',
              content: item.zgNotes,
              isButton: item.isButton,
              stat: item.stat,
            });
          });
        }
      });
    },
    handleAppeal(id, stat) {
      if (stat == '1') {
        return this.$message.info('正在申诉中...');
      } else if (stat == '3') {
        return this.$message.info('申诉通道已被监督处关闭,无法申诉!');
      }
      this.bizId = id;
      this.showAppeal = true;
      this.getFileList(id);
    },
    getFileList(id) {
      const params = {
        id,
      };
      this.currentId = id;
      request
        .post(`/bis/insp/BisInspZgPblmRecord/getAuditListInfo`, params)
        .then((res) => {
          this.fileArray = res.data.gwComFiles;
        });
    },
    submitAppeal() {
      this.$refs.appealRef.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          const params = {
            id: this.bizId,
            appealContent: this.appealForm.appealContent,
          };
          request
            .post(`/bis/insp/BisInspZgPblmRecord/overdueStatementAudit`, params)
            .then((res) => {
              if (res.success) {
                this.confirmLoading = false;
                this.$message.success('申诉成功!');
                this.getPblmProcInstHistoryOver();
                this.appealForm.appealContent = '';
                this.showAppeal = false;
                this.fileList = [];
              } else {
                this.$message.warning(res.message);
              }
            });
        } else {
          return false;
        }
      });
    },
    handleChange(info) {
      this.fileList = info.fileList;
      const status = info.file.status;
      if (status === 'done') {
        this.$message.success(`${info.file.name}上传成功!`);
      } else if (status === 'error') {
        this.$message.error(`${info.file.name}上传失败,请联系管理员!`);
      }
    },
    appealRecord(id) {
      this.showAppealRecord = true;
      this.appealRecordData = null;
      this.appealRecordLine = [];
      this.gwComFiles = [];
      const params = {
        id,
      };
      request
        .post(`/bis/insp/BisInspZgPblmRecord/getAuditListInfo`, params)
        .then((res) => {
          if (res.success) {
            this.appealRecordData = res.data;
            res.data.adjustAudits.forEach((item) => {
              if (item.opStatus !== '正在进行中') {
                this.appealRecordLine.push({
                  id: item.id,
                  timestamp: formatDateTime2(item.intm),
                  type: 'check-circle',
                  color: '#0bbd87',
                  workflowStatName: item.workflowStatName,
                  content: `${item.auditPersName} - ${item.opStatus} - ${item.adjustRcord}`,
                });
              } else {
                this.appealRecordLine.push({
                  timestamp: formatDateTime(new Date()),
                  type: 'ellipsis',
                  workflowStatName: item.workflowStatName,
                  content: '正在进行中',
                });
              }
            });
            this.appealContent = res.data.appealContent || '';
            this.gwComFiles = res.data.gwComFiles;
          } else {
            this.$message.warning(res.message);
          }
        });
    },
    // 下载
    downloadFile(downloadFiles, fileName) {
      request
        .get(`file/downFile/` + downloadFiles, { responseType: 'arraybuffer' })
        .then((res) => {
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
          const objectUrl = URL.createObjectURL(blob);
          // window.location.href = objectUrl;
          const link = document.createElement('a');
          link.href = objectUrl;
          link.download = fileName; // 文件名
          link.click(); // 下载文件
          URL.revokeObjectURL(objectUrl); // 释放内存
        });
    },
    removeFile(id, index) {
      this.$confirm({
        title: '提示',
        content: '此操作将永久删除该文件, 是否继续?',
        okType: 'warning',
        onOk: () => {
          deleteFileById(id, this.userId).then((res) => {
            if (res.success) {
              this.getFileList(this.currentId);
            } else {
              this.failInfo();
            }
          });
        },
      });
    },
  },
};
</script>

<style lang='less' scoped>
.is-stat {
  color: #ccc;
}
</style>
