<template>
  <div>
    <div class="tool-btn" style="width: 800px; margin: 0 auto; text-align: right;">
      <el-button size="small" type="primary" icon="el-icon-printer" v-print="printConfig" @click="isPrintPage = true">打印</el-button>
    </div>
  
    <div id="acceptDoc" class="doc-page" v-loading="loading">
      <div :class="['doc-header', { printCls: isPrintPage }]">
        <h3 class="page-title" style="height: 60px; line-height: 60px; margin: 0;">{{ teantData.tenantName }}</h3>
        <h3 class="page-title" style="margin: 5px 0 16px;">研发项目验收资料</h3>

        <div class="project-basic-info">
          <div class="info-row">{{ `研发项目名称：${ selProject.xmmc || '' }` }}</div>
          <div class="info-row">{{ `项目负责人：${ selProject.xmfzrxm || '' }` }}</div>
          <div class="info-row">{{ `项目申请单位：${ selProject.xmsqdw || '' }` }}</div>
          <div class="info-row">{{ `项目执行期：${ getXmDateRange || '' }` }}</div>
          <div class="info-row">
            <span>填报时间：</span>
            <span>
              <el-date-picker v-show="!isPrintPage" v-model="formData.tbsj" value-format="yyyy-MM-dd" />
              <span v-show="isPrintPage">{{ formData.tbsj }}</span>
            </span>
          </div>
        </div>
      </div>

      <!-- 打印强制分页 -->
      <div style="page-break-after: always;"></div>

      <h3 class="page-title" style="margin: 24px 0 16px;">研发项目验收申请表</h3>
      <table style="margin-top: 20px;">
        <tbody>
          <tr>
            <td class="doc-label">研发项目名称</td>
            <td class="doc-input">
              <project-select
                v-show="!isPrintPage"
                v-model="currProjectId"
                @change="handleProjectChange"
              ></project-select>
              <span v-show="isPrintPage">{{ selProject.xmmc }}</span>
            </td>
            <td class="doc-label">项目申请单位</td>
            <td class="doc-input">
              {{ selProject.xmsqdw }}
            </td>
          </tr>
          <tr>
            <td class="doc-label">项目负责人</td>
            <td class="doc-input">{{ selProject.xmfzrxm }} </td>
            <td class="doc-label">研究类型</td>
            <td class="doc-input">{{ selProject.yjlx }}</td>
          </tr>

          <tr>
            <td class="doc-label">研发开始时间</td>
            <td class="doc-input">{{ selProject.xmkssj }} </td>
            <td class="doc-label">研发结束时间</td>
            <td class="doc-input">{{ selProject.xmjssj }}</td>
          </tr>

          <tr>
            <td class="doc-label">项目来源</td>
            <td class="doc-input">{{ selProject.xmly }} </td>
            <td class="doc-label">项目开展形式</td>
            <td class="doc-input">{{ selProject.xmkzxs }}</td>
          </tr>

          <tr>
            <td class="doc-label">预期成果形式</td>
            <td class="doc-input">
              <div style="padding: 12px;">
                <div v-for="(item, index) of selProject.yqcgxs.split(',')" :key="index">{{ item }}</div>
              </div>
            </td>
            <td class="doc-label">项目技术经济目标</td>
            <td class="doc-input">
              <div style="padding: 12px;">
                <div v-for="(item, index) of selProject.xmjsjjmb.split(',')" :key="index">{{ item }}</div>
              </div>
            </td>
          </tr>

        </tbody>
      </table>

      <avue-form v-show="!isPrintPage" v-model="formData" :option="option" style="margin-top: 30px; padding: 0;">
        <template slot="ysbgLabel">
          <label>验收报告</label>
          <div style="position: absolute; top: 0; left: 220px; z-index: 1;">
            <file-download-btn templateKey="研发项目管理-项目结题-验收报告"></file-download-btn>
          </div>
        </template>
        <template slot="jsbgLabel">
          <label>技术报告</label>
          <div style="position: absolute; top: 0; left: 220px; z-index: 1;">
            <file-download-btn templateKey="研发项目管理-项目结题-技术报告"></file-download-btn>
          </div>
        </template>
        <template slot="cgbgLabel">
          <label>成果报告</label>
          <div style="position: absolute; top: 0; left: 220px; z-index: 1;">
            <file-download-btn templateKey="研发项目管理-项目结题-成果报告"></file-download-btn>
          </div>
        </template>
        <template slot="xybgLabel">
          <label>效益报告</label>
          <div style="position: absolute; top: 0; left: 220px; z-index: 1;">
            <file-download-btn templateKey="研发项目管理-项目结题-效益报告"></file-download-btn>
          </div>
        </template>
        <template slot="yspwLabel">
          <label>验收批文</label>
          <div style="position: absolute; top: 0; left: 220px; z-index: 1;">
            <file-download-btn templateKey="研发项目管理-项目结题-验收批文"></file-download-btn>
          </div>
        </template>
      </avue-form>

      <div v-show="isPrintPage" class="file-list" style="margin-top: 30px;">
        <div class="file-list-item" style="display: flex; margin-bottom: 18px;">
          <div class="name">验收报告：</div>
          <div class="file-wrap">
            <div v-for="(item, idx) of formData.ysbg" :key="idx">{{ item.label }}</div>
          </div>
        </div>
        <div class="file-list-item" style="display: flex; margin-bottom: 18px;">
          <div class="name">技术报告：</div>
          <div class="file-wrap">
            <div v-for="(item, idx) of formData.jsbg" :key="idx">{{ item.label }}</div>
          </div>
        </div>
        <div class="file-list-item" style="display: flex; margin-bottom: 18px;">
          <div class="name">成果报告：</div>
          <div class="file-wrap">
            <div v-for="(item, idx) of formData.cgbg" :key="idx">{{ item.label }}</div>
          </div>
        </div>
        <div class="file-list-item" style="display: flex; margin-bottom: 18px;">
          <div class="name">效益报告：</div>
          <div class="file-wrap">
            <div v-for="(item, idx) of formData.xybg" :key="idx">{{ item.label }}</div>
          </div>
        </div>
        <div class="file-list-item" style="display: flex; margin-bottom: 18px;">
          <div class="name">验收批文：</div>
          <div class="file-wrap">
            <div v-for="(item, idx) of formData.yspw" :key="idx">{{ item.label }}</div>
          </div>
        </div>
      </div>

      <p v-show="!isPrintPage" class="tip">注：可一次上传多个相关文件（文档、表格、图片等）。 支持格式：DOC, PDF, Excel, PNG, JPG, PPT 等。 请确保文件内容清晰有效。</p>

      <div v-show="!isPrintPage" class="btn-wrap" style="text-align: center; margin-top: 30px;">
        <template v-if="!projectIsEnd">
          <el-button type="primary" style="width: 160px;" @click="handleSaveBtn(0)">保 存</el-button>
          <el-button type="primary" style="width: 160px;" @click="handleSaveBtn(2)">确定结题</el-button>
        </template>
        <el-button v-else type="primary" style="width: 160px;" @click="handleSaveBtn(1)">取消结题</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import projectSelect from "@/components/project-select";
import secondUnitCascader from "@/components/second-unit-cascader";
import fileDownloadBtn from "@/components/file-download-btn";
import { save, getDetail } from "@/api/projectManage/accept";
import moment from "moment";
import { mapGetters } from "vuex";
import { getDetail as getTenantDetail } from '@/api/system/tenant';
import { downloadFileByUrl } from "@/util/util";


export default {
  components: {
    projectSelect,
    secondUnitCascader,
    fileDownloadBtn
  },
  props: {
    projectId: [String, Number]
  },
  data() {
    return {
      formData: {},

      loading: false,
      projectList: [],
      selProject: {
        yqcgxs: '',
        xmjsjjmb: '',
      },

      currProjectId: '',

      teantData: {},

      isPrintPage: false,
      printConfig: {
        el: '#acceptDoc', //被打印部分的id
        closeCallback: () => {
          this.isPrintPage = false;
        }
      },

      // 项目是否已结束
      projectIsEnd: false,
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    getXmDateRange() {
      if (this.selProject.xmkssj && this.selProject.xmjssj) {
        let xmkssj = moment(this.selProject.xmkssj).format('yyyy年MM月DD日');
        let xmjssj = moment(this.selProject.xmjssj).format('yyyy年MM月DD日')
        return `${xmkssj}至${xmjssj}`;
      }
      return `年 月 日至 年 月 日`;
    },
    option() {
      return {
        menuBtn: false,
        labelWidth: 75,
        column: [
          {
            label: "验收报告",
            prop: "ysbg",
            type: "upload",
            multiple: true,
            span: 24,
            dataType: "object",
            propsHttp: {
              url: "link",
              name: "originalName",
              res: "data",
            },
            action: '/api/kd-resource/oss/endpoint/put-file',
            uploadPreview: (file, column, done) => {
              downloadFileByUrl(file.url, file.name);
              return;
            },
            disabled: !this.currProjectId
          },
          {
            label: "技术报告",
            prop: "jsbg",
            type: "upload",
            multiple: true,
            span: 24,
            dataType: "object",
            propsHttp: {
              url: "link",
              name: "originalName",
              res: "data",
            },
            action: '/api/kd-resource/oss/endpoint/put-file',
            uploadPreview: (file, column, done) => {
              downloadFileByUrl(file.url, file.name);
              return;
            },
            disabled: !this.currProjectId
          },
          {
            label: "成果报告",
            prop: "cgbg",
            type: "upload",
            multiple: true,
            span: 24,
            dataType: "object",
            propsHttp: {
              url: "link",
              name: "originalName",
              res: "data",
            },
            action: '/api/kd-resource/oss/endpoint/put-file',
            uploadPreview: (file, column, done) => {
              downloadFileByUrl(file.url, file.name);
              return;
            },
            disabled: !this.currProjectId
          },
          {
            label: "效益报告",
            prop: "xybg",
            type: "upload",
            multiple: true,
            span: 24,
            dataType: "object",
            propsHttp: {
              url: "link",
              name: "originalName",
              res: "data",
            },
            action: '/api/kd-resource/oss/endpoint/put-file',
            uploadPreview: (file, column, done) => {
              downloadFileByUrl(file.url, file.name);
              return;
            },
            disabled: !this.currProjectId
          },
          {
            label: "验收批文",
            prop: "yspw",
            type: "upload",
            multiple: true,
            span: 24,
            dataType: "object",
            action: '/api/kd-resource/oss/endpoint/put-file',
            uploadPreview: (file, column, done) => {
              downloadFileByUrl(file.url, file.name);
              return;
            },
            propsHttp: {
              url: "link",
              name: "originalName",
              res: "data",
            },
            disabled: !this.currProjectId
          },
        ],
      }
    }
  },
  watch: {
    currProjectId() {
      this.getImplementDetail();
    }
  },
  mounted() {
    this.getTenantDetailFunc(this.userInfo.tenant_id);
    this.currProjectId = this.projectId || '';
  },
  methods: {
    // 获取租户详情信息
    getTenantDetailFunc(tenantId) {
      getTenantDetail(tenantId).then(({ data }) => {
        if (data.code == 200) {
          this.teantData = data.data;
        }
      });
    },
    getImplementDetail() {
      this.loading = true;
      getDetail({ xmId: this.currProjectId, yearAndMonth: this.yearAndMonth }).then(({ data }) => {
        this.loading = false;
        if (data.code == 200 && data.data && Object.keys(data.data).length) {
          this.formData = {
            id: data.data.id,
            xmId: data.data.xmId,
            tbsj: data.data.tbsj,
            ysbg: data.data.ysbg ? JSON.parse(data.data.ysbg) : [],
            jsbg: data.data.jsbg ? JSON.parse(data.data.jsbg) : [],
            cgbg: data.data.cgbg ? JSON.parse(data.data.cgbg) : [],
            xybg: data.data.xybg ? JSON.parse(data.data.xybg) : [],
            yspw: data.data.yspw ? JSON.parse(data.data.yspw) : [],
          };
        } else {
          this.formData = {
            id: undefined,
            tbsj: '',
            ysbg: [],
            jsbg: [],
            cgbg: [],
            xybg: [],
            yspw: [],
          };
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    handleProjectChange(data) {
      this.selProject = data;
      this.projectIsEnd = data.status == 2 ? true : false;
    },
    validForm() {
      let errorText = '';
      if (!this.formData.tbsj) {
        errorText = '请选择填报时间';
      } else if (!this.currProjectId) {
        errorText = '请选择填报的项目';
      }

      return errorText;
    },
    /**
     * 提交表单
     * @param status 0(暂存)、2(确定结题)、1(取消结题)
     */
    handleSaveBtn(operateType) {
      let errorText = this.validForm();
      if (errorText) {
        this.$message.error(errorText+'！');
        return;
      }

      const params = { ...this.formData, xmId: this.currProjectId, status: operateType };
      params.ysbg = JSON.stringify(params.ysbg);
      params.jsbg = JSON.stringify(params.jsbg);
      params.cgbg = JSON.stringify(params.cgbg);
      params.xybg = JSON.stringify(params.xybg);
      params.yspw = JSON.stringify(params.yspw);

      this.saveData(params, operateType);
    },
    saveData(params, operateType) {
      save(params).then(({ data }) => {
        if (data.code == 200) {
          let msgObj = {
            0: '保存成功',
            1: '项目取消结题成功',
            2: '项目结题成功'
          };
          if (operateType == 2) {
            this.projectIsEnd = true;
          } else {
            this.projectIsEnd = false;
          }
          this.$message.success(`${msgObj[operateType]}!`);
        }
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.page-title {
  text-align: center;
  font-size: 26px;
}

.project-basic-info .info-row {
  line-height: 26px;
  color: #333;
}

.doc-header.printCls {
  padding-top: 50mm;
  .project-basic-info {
    padding-top: 20mm;
    padding-left: 30mm;
    font-size: 20px;
    font-weight: 600;
    .info-row {
      line-height: 50px;
    }
  }
}

.doc-page {
  width: 760px;
  margin: 0 auto 30px;
}
table {
  width: 100%;
  border: 1px solid #333;
}
.doc-label {
  text-align: center;
  padding: 6px;
  color: #777;
  font-size: 14px;
  width: 15%;
}
.doc-input {
  text-align: center;
  color: #333;
  width: 35%;
  height: 40px;
}

.el-input__inner {
  border: none;
}
tr td {
  border: 1px solid #333;
  font-size: 14px;
}

.tip {
  position: relative;
  top: 0;
  color: red;
  padding-left: 75px;
  margin-top: 0;
  font-size: 12px;
}
</style>
