<template>
  <div v-loading="loading">
    <div class="header-btn">
      <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAddClick">新增</el-button>
      <el-button size="small" type="primary" icon="el-icon-printer" v-print="printConfig" @click="isPrintPage = true">打印</el-button>
    </div>
    
    <div id="outsourcingWrap" class="doc-page">
      <h3 class="page-title">委外项目管理</h3>
      <year-month-select v-show="!isPrintPage" v-model="params.yearAndMonth" :showMonth="false"></year-month-select>
      <table class="doc-table">
        <tbody>
          <tr>
            <td class="doc-label">研发项目名称</td>
            <td class="doc-input">
              <project-select v-show="!isPrintPage" v-model="params.xmId" @change="handleProjectChange"></project-select>
              <span v-show="isPrintPage">{{ selProject.xmmc }}</span>
            </td>
            <td class="doc-label">研发项目编号</td>
            <td class="doc-input">{{ selProject.xmbh }}</td>
          </tr>
          <tr>
            <td colspan="4">
              <table class="child-table">
                <thead>
                  <tr>
                    <td width="10%">受托方全称</td>
                    <td width="10%">受托方类型</td>
                    <td width="10%">合同名称</td>
                    <td width="10%">委外费用金额（万元）</td>
                    <td width="8%">是否完成技术合同登记</td>
                    <td width="8%">技术合同登记类型</td>
                    <td width="8%">技术合同登记金额（万元）</td>
                    <td width="31%">附件上传</td>
                    <td v-show="!isPrintPage" width="5%" class="operate-col">操作</td>
                  </tr>
                </thead>
                <tbody>
                  <template v-if="list.length">
                    <tr v-for="(item, index) of  list" :key="index">
                      <td v-for="key of colKey" :key="key" style="padding: 0;">
                        <template v-if="key == 'fileTypeList'">
                          <div class="file-list">
                            <div class="file-list-item" v-for="(typeItem, typeIdx) of item[key]" :key="typeIdx">
                              <div class="file-name">{{ typeItem.label }}</div>
                              <div class="file-url" style="text-align: left; line-height: 16px;">
                                <a
                                  v-for="(file, fileIdx) of typeItem.fileList"
                                  :key="fileIdx"
                                  style="display: block; margin: 0 4px; cursor: pointer; color: #409EFF; text-decoration: underline;"
                                  type="primary"
                                  @click="handleDownloadFile(file)"
                                >
                                  {{ file.label }}
                                </a>
                              </div>
                            </div>
                          </div>
                        </template>
                        <span v-else>{{ item[key] }}</span>
                      </td>
                      <td class="operate-col" width="10%">
                        <el-button type="text" class="printHide" @click="handleEditClick(item)">编辑</el-button>
                        <el-button type="text" class="printHide" style="margin-left: 0;" @click="handleDel(item)">删除</el-button>
                      </td>
                    </tr>
                  </template>
                  <template v-else>
                    <td colspan="9" style="border: none;"><el-empty description="暂无数据"></el-empty></td>
                  </template>
                </tbody>
              </table>
            </td>
          </tr>
        </tbody>
      </table>

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

      <el-drawer
        :visible.sync="drawerVisible"
        :title="drawerTitle"
        modal-append-to-body
        append-to-body
        size="500px"
        destroy-on-close
      >
        <avue-form v-model="form" :option="option" @submit="handleSubmit" @reset-change="handleResetForm">
        </avue-form>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import yearMonthSelect from "@/components/year-month-select";
import projectSelect from "@/components/project-select";
import moment from "moment";
import { getList, submit, remove } from "@/api/projectManage/outsourcingDoc";
import { downloadFileByUrl } from "@/util/util";

export default {
  props: {
    projectId: [String, Number]
  },
  components: {
    yearMonthSelect,
    projectSelect
  },
  data() {
    return {
      printBill: {
        el: '#printWrap',
        preview: true  
      },
      loading: false,

      list: [],
      colKey: ['stfqc', 'stflx', 'htmc', 'wwfyje', 'sfwcjshtdj', 'jshtdjlx', 'jshtdjje', 'fileTypeList'],

      selProject: {},

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

      drawerTitle: '',
      drawerVisible: false,
      option:{
        labelWidth: 170,
        emptyText: "取消",
        column:[
          {
            label: '受托方全称',
            prop: 'stfqc',
            span: 24,
            rules: [{
              required: true,
              message: "请输入受托方全称",
              trigger: "blur"
            }]
          },
          {
            label: '受托方类型',
            prop: 'stflx',
            span: 24,
            type: 'select',
            dicUrl: '/api/kd-system/dict/dictionary?code=trustee_type',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            rules: [{
              required: true,
              message: "请选择受托方类型",
              trigger: "blur"
            }]
          },
          {
            label: '合同名称',
            prop: 'htmc',
            span: 24
          },
          {
            label: '委外费用金额(万元)',
            prop: 'wwfyje',
            span: 24,
            type: 'number',
            min: 0,
            precision: 2,
          },
          {
            label: '是否完成技术合同登记',
            prop: 'sfwcjshtdj',
            span: 24,
            type: 'select',
            dicUrl: '/api/kd-system/dict/dictionary?code=yes_or_no',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            rules: [{
              required: true,
              message: "请选择",
              trigger: "blur"
            }]
          },
          {
            label: '技术合同类型',
            prop: 'jshtdjlx',
            span: 24,
            type: 'select',
            dicUrl: '/api/kd-system/dict/dictionary?code=contract_registration_type',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
          },
          {
            label: '技术合同登记金额(万元)',
            prop: 'jshtdjje',
            span: 24,
            type: 'number',
            min: 0,
            precision: 2,
          },
          {
            label: "技术合同协议",
            prop: "jshtxy",
            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;
            },
          },
          
          {
            label: "委外费用发票",
            prop: "wwfyfp",
            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;
            },
          },
          {
            label: "技术合同登记证明",
            prop: "jshtdjzm",
            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;
            },
          },
          {
            label: "受托方交付成果",
            prop: "stfjfcg",
            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;
            },
          },
          {
            label: "其他资料",
            prop: "qtzl",
            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;
            },
          },
        ]
      },
      form: {},
      params: {
        yearAndMonth: moment(new Date()).format('yyyy'),
        xmId: ''
      },
    };
  },
  watch: {
    "params.xmId"() {
      this.getListData();
    },
    "params.yearAndMonth"() {
      this.getListData();
    },
  },
  mounted() {
    this.params.xmId = this.projectId;
  },
  methods: {
    handleProjectChange(data) {
      this.selProject = data;
    },
    getListData() {
      if (!this.params.xmId || !this.params.yearAndMonth) {
        return;
      }
      this.loading = true;
      getList(1, 99999, this.params).then(({ data }) => {
        this.loading = false;
        if (data.code == 200) {
          this.list = data.data.records.map(item => {
            item.wwfyje = (item.wwfyje || 0).toFixed(2);
            item.jshtdjje = (item.jshtdjje || 0).toFixed(2);
            item.jshtxy = item.jshtxy ? JSON.parse(item.jshtxy) : [];
            item.wwfyfp = item.wwfyfp ? JSON.parse(item.wwfyfp) : [];
            item.jshtdjzm = item.jshtdjzm ? JSON.parse(item.jshtdjzm) : [];
            item.stfjfcg = item.stfjfcg ? JSON.parse(item.stfjfcg) : [];
            item.qtzl = item.qtzl ? JSON.parse(item.qtzl) : [];
            item.fileTypeList = [{
              label: '技术合同协议',
              fileList: item.jshtxy
            }, {
              label: '委外费用发票',
              fileList: item.wwfyfp
            }, {
              label: '技术合同登记证明',
              fileList: item.jshtdjzm
            }, {
              label: '受托方交付成果',
              fileList: item.stfjfcg
            }, {
              label: '其他资料',
              fileList: item.qtzl
            }];

            return item;
          });
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    handleAddClick() {
      if (!this.params.xmId) {
        this.$message.error("请选择所属项目!");
        return;
      }
      this.form = {};
      this.drawerVisible = true;
      this.drawerTitle = '新增委外信息';
    },
    handleEditClick(data) {
      this.drawerVisible = true;
      this.form = { ...data };
      this.drawerTitle = '编辑委外信息';
    },
    handleSubmit(form, done) {
      const params = { ...form, yearAndMonth: this.params.yearAndMonth, xmId: this.params.xmId };
      params.jshtxy = JSON.stringify(params.jshtxy);
      params.wwfyfp = JSON.stringify(params.wwfyfp);
      params.jshtdjzm = JSON.stringify(params.jshtdjzm);
      params.stfjfcg = JSON.stringify(params.stfjfcg);
      params.qtzl = JSON.stringify(params.qtzl);

      submit(params).then(({ data }) => {
        if (data.code == 200) {
          this.$message.success("操作成功!");
          this.getListData();
          this.drawerVisible = false;
        }
        done();
      }).catch(() => {
        done();
      });
    },
    handleDownloadFile(file) {
      downloadFileByUrl(file.value, file.label);
    },
    handleResetForm() {
      this.drawerVisible = false;
    },
    handleDel(records) {
      this.$confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        remove(records.id).then(({ data }) => {
          if (data.code == 200) {
            this.$message.success("删除成功!");
            this.getListData();
          }
        });
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.page-title {
  text-align: center;
  font-size: 24px;
  padding: 24px 0 20px;
  margin: 0;
}

@media print {
  .doc-page {
    zoom: 60%;
  }
}

.doc-page {
  width: 1200px;
  height: auto;
  margin: 0 auto;
}
.header-btn {
  width: 1200px;
  margin: 0 auto;
  text-align: right;
}
.doc-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%;
}
.doc-table {
  padding: 0;
}
.doc-table tr td {
  border: 1px solid #333;
}


.child-table {
  border: none;
}
.child-table tr {
  td {
    border: none;
    border-right: 1px solid #333;
    padding: 0 6px;
    text-align: center;
    color: #666;
    font-size: 14px; 
    &:last-child {
      border: none;
    }
  }
}

.child-table thead tr {
  border-bottom: 1px solid #333;
}

.child-table tbody tr {
  border-bottom: 1px solid #333;
  &:last-child {
    border-bottom: 0;
  } 
}

.file-list {
  &-item {
    display: flex;
    border-bottom: 1px solid #333;
    line-height: 32px;
    text-align: center;
    word-wrap: break-word;
    // align-items: center;
    .file-name {
      width: 40%;
      border-right: 1px solid #333;
    }
    .file-url {
      width: 60%;
    }
    &:last-child {
      border-bottom: 0;
    }
  }
}

.tip {
  color: red;
  margin-top: 12px;
  font-size: 12px;
}
</style>
