<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['cs:csContractDetails:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['cs:csContractDetails:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['cs:csContractDetails:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['cs:csContractDetails:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['cs:csContractDetails:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-download" size="mini" @click="handleExportTemplate"
          v-hasPermi="['cs:csContractDetails:export']">导出模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain size="mini" @click="handleSearch">高级搜索</el-button>
      </el-col>
      <el-col :span="8">
        <span style="padding-right: 10px;">表格设置</span>
        <el-select v-model="tableHeaderList" multiple collapse-tags placeholder="请选择" @change="changeSelect">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div v-if="showSearch" ref="showSearch" class="searchForm">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="关键词">
          <el-input placeholder="请输入关键词" v-model="queryParams.keyword" />
        </el-form-item>
        <el-form-item label="签订时间" prop="signingTime">
          <el-date-picker clearable v-model="queryParams.signingTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择签订时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="终止时间" prop="endTime">
          <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择终止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="需方(单位)" prop="demandingSide">
          <el-input v-model="queryParams.demandingSide" placeholder="请输入需方(单位)" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="项目/合同名称" prop="contractName">
          <el-input v-model="queryParams.contractName" placeholder="请输入项目/合同名称" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="合同金额(万元)" prop="contractPrice">
          <el-input v-model="queryParams.contractPrice" placeholder="请输入合同金额(万元)" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="合同类别" prop="contractClassId">
          <el-input v-model="queryParams.contractClassId" placeholder="请输入合同类别" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="隶属部门" prop="sort">
          <el-input v-model="queryParams.sort" placeholder="请输入隶属部门" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="经办人" prop="memberUserId">
          <el-input v-model="queryParams.memberUserId" placeholder="请输入经办人" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="提交时间" prop="dateRange">
          <el-date-picker clearable v-model="queryParams.dateRange" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin: 10px 0;">
      1.已完成经法系统或线下审批，并且合同双方盖章清晰、骑缝章无缺失；
      <br />
      2.要求合同法人或授权人签字、经办人签字、合同签订日期明确；
      <br />
      3.归档的合同文件资料，原则上必须为原件。如原件由于特殊原因用于报批不能归档或必须由相关部门保留的，需提供复印件并备注原件保留部门或缺失原因，以备查阅；
      <br />
      4.归档的合同文件电子版扫描件；
      <br />
      5.合同资料转移时须签署入库移交单；
      <br />
      6.合同类别分为采购类、销售类、试验检测类、其他
    </div>
    <el-table v-loading="loading" :data="csContractDetailsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="sort">
        <template slot-scope="scope">
          {{ ((queryParams.pageNum - 1) * queryParams.pageSize) + (scope.$index + 1) }}
        </template>
      </el-table-column>
      <el-table-column label="部门合同编号" align="center" prop="departmentContractNumber"
        v-if="tableHeaderList.indexOf('departmentContractNumber') != -1" />
      <!-- <el-table-column label="合同号" align="center" prop="contractNumber"
        v-if="tableHeaderList.indexOf('contractNumber') != -1" /> -->
      <el-table-column label="签订时间" align="center" prop="signingTime"
        v-if="tableHeaderList.indexOf('signingTime') != -1" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="终止时间" align="center" prop="endTime" v-if="tableHeaderList.indexOf('endTime') != -1"
        width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目/合同名称" align="center" prop="contractName"
        v-if="tableHeaderList.indexOf('contractName') != -1" />
      <el-table-column label="合同金额(万元)" align="center" prop="contractPrice"
        v-if="tableHeaderList.indexOf('contractPrice') != -1" />
      <el-table-column label="合同类别名" align="center" prop="contractClassName"
        v-if="tableHeaderList.indexOf('contractClassName') != -1" />
      <el-table-column label="需方" align="center" prop="demandingSide"
        v-if="tableHeaderList.indexOf('demandingSide') != -1" />
      <el-table-column label="供方" align="center" prop="supplier" v-if="tableHeaderList.indexOf('supplier') != -1" />
      <el-table-column label="需方经办人" align="center" prop="memberUserName"
        v-if="tableHeaderList.indexOf('memberUserName') != -1" />
      <el-table-column label="供方经办人" align="center" prop="supplierUserName"
                       v-if="tableHeaderList.indexOf('supplierUserName') != -1" />
      <el-table-column label="合同状态" align="center" prop="contractStatus"
        v-if="tableHeaderList.indexOf('content') != -1" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['cs:csContractDetails:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['cs:csContractDetails:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改合同信息详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="相关资源名" prop="resName">
          <el-input v-model="form.resName" placeholder="请输入相关资源名" />
        </el-form-item>
        <el-form-item label="部门合同编号" prop="departmentContractNumber">
          <el-input v-model="form.departmentContractNumber" placeholder="请输入部门合同编号" />
        </el-form-item>
        <el-form-item label="合同号" prop="contractNumber">
          <el-input v-model="form.contractNumber" placeholder="请输入合同号" />
        </el-form-item>
        <el-form-item label="签订时间" prop="signingTime">
          <el-date-picker clearable v-model="form.signingTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择签订时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="终止时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择终止时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="需方" prop="demandingSide">
          <el-input v-model="form.demandingSide" placeholder="请输入需方" />
        </el-form-item>
        <el-form-item label="供方" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供方" />
        </el-form-item>
        <el-form-item label="二级单位(部门/学院)名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入二级单位(部门/学院)名称" />
        </el-form-item>
        <el-form-item label="隶属部门" prop="affiliationDept">
          <el-input v-model="form.affiliationDept" placeholder="请输入隶属部门" />
        </el-form-item>
        <el-form-item label="合同类别名" prop="contractClassName">
          <el-input v-model="form.contractClassName" placeholder="请输入合同类别名" />
        </el-form-item>
        <el-form-item label="需方经办人名" prop="memberUserName">
          <el-input v-model="form.memberUserName" placeholder="请输入需方经办人名" />
        </el-form-item>
        <el-form-item label="供方经办人名" prop="supplierUserName">
          <el-input v-model="form.supplierUserName" placeholder="请输入供方经办人名" />
        </el-form-item>
        <el-form-item label="项目/合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入项目/合同名称" />
        </el-form-item>
        <el-form-item label="合同金额(万元)" prop="contractPrice">
          <el-input v-model="form.contractPrice" placeholder="请输入合同金额(万元)" />
        </el-form-item>
        <el-form-item label="存档位置" prop="archiveLocation">
          <el-input v-model="form.archiveLocation" placeholder="请输入存档位置" />
        </el-form-item>
        <el-form-item label="是否原件" prop="isOriginal">
          <el-radio-group v-model="form.isOriginal">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原件缺失原因" prop="lackReason">
          <el-input v-model="form.lackReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="附件" prop="annexUrl">
          <el-upload class="upload-demo" :action="$baseUrl + '/api/common/uploadFileLocal'" :limit="1"
                     :on-success="handleSuccess" :file-list="fileList">
            <el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持扩展名：pdf.doc.jpg.png…</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="入库数量(份)" prop="warehousingTotal">
          <el-input v-model="form.warehousingTotal" placeholder="请输入入库数量(份)" />
        </el-form-item>
        <el-form-item label="入库时间" prop="warehousingTime">
          <el-date-picker clearable v-model="form.warehousingTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择入库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listCsContractDetails, getCsContractDetails, delCsContractDetails, addCsContractDetails, updateCsContractDetails } from "@/api/cs/csContractDetails";

export default {
  name: "CsContractDetails",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 合同信息详情表格数据
      csContractDetailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        dateRange: [],
        resId: null,
        resName: null,
        resType: null,
        departmentContractNumber: null,
        contractNumber: null,
        signingTime: null,
        endTime: null,
        demandingSide: null,
        supplier: null,
        deptId: null,
        deptName: null,
        companyClassId: null,
        affiliationDept: null,
        contractClassId: null,
        contractClassName: null,
        memberUserId: null,
        memberUserName: null,
        supplierUserName: null,
        contractName: null,
        contractPrice: null,
        archiveLocation: null,
        isOriginal: null,
        lackReason: null,
        annexUrl: null,
        warehousingTotal: null,
        warehousingTime: null,
        content: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      options: [{
        value: 'departmentContractNumber',
        label: '部门合同编号'
      },
      //  {
      //   value: 'contractNumber',
      //   label: '合同号'
      // },
       {
        value: 'signingTime',
        label: '签订时间'
      }, {
        value: 'endTime',
        label: '终止时间'
      }, {
        value: 'contractName',
        label: '项目'
      }, {
        value: 'contractPrice',
        label: '合同金额(万元)'
      }, {
        value: 'contractClassName',
        label: '合同类别名'
      }, {
        value: 'demandingSide',
        label: '需方'
      }, {
        value: 'supplier',
        label: '供方'
      },
      //  {
      //   value: 'affiliationDept',
      //   label: '隶属部门'
      // }, 
      {
        value: 'memberUserId',
        label: '经办人'
      }, 
      // {
      //   value: 'warehousingTotal',
      //   label: '入库数量(份)'
      // },
      //  {
      //   value: 'isOriginal',
      //   label: '是否原件'
      // }, 
      // {
      //   value: 'lackReason',
      //   label: '原件缺失原因'
      // }, {
      //   value: 'annexUrl',
      //   label: '附件明细'
      // }, {
      //   value: 'warehousingTime',
      //   label: '入库时间'
      // }, {
      //   value: 'archiveLocation',
      //   label: '存档位置'
      // },
       {
        value: 'contractStatus',
        label: '合同状态'
      }, 
      // {
      //   value: 'remarks',
      //   label: '备注'
      // }
    ],
      tableHeaderList: ['departmentContractNumber', 'contractNumber', 'signingTime', 'endTime', 'contractName', 'contractPrice', 'contractClassName', 'demandingSide', 'supplier', 'affiliationDept', 'memberUserName', 'supplierUserName', 'warehousingTotal', 'isOriginal', 'lackReason', 'annexUrl', 'warehousingTime', 'archiveLocation', 'contractStatus', 'remarks'],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/cs/csContractDetails/importCsContractDetails"
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // document.addEventListener(
    //   "click",
    //   (e) => {
    //     let showSearch = this.$refs.showSearch;
    //     if (!showSearch.contains(e.target)) {
    //       this.showSearch = false;
    //     }
    //   },
    //   true
    // );
    this.tableHeaderList = localStorage.getItem('contractManagement') ? localStorage.getItem('contractManagement').split(',') : this.tableHeaderList
  },
  methods: {
    
    changeSelect(e, t) {
      localStorage.setItem('contractManagement', e)
    },
    /** 查询合同信息详情列表 */
    getList() {
      this.loading = true;
      if (null != this.queryParams.dateRange && '' != this.queryParams.dateRange) {
        this.queryParams["beginCreateAt"] = this.queryParams.dateRange[0];
        this.queryParams["endCreateAt"] = this.queryParams.dateRange[1];
      }
      listCsContractDetails(this.queryParams).then(response => {
        this.csContractDetailsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleSearch() {
      this.showSearch = !this.showSearch
    },
    handleSuccess(response){
      this.form.annexUrl = response.url
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        contractDetailsId: null,
        resId: null,
        resName: null,
        resType: null,
        departmentContractNumber: null,
        contractNumber: null,
        signingTime: null,
        endTime: null,
        demandingSide: null,
        supplier: null,
        deptId: null,
        deptName: null,
        companyClassId: null,
        affiliationDept: null,
        contractClassId: null,
        contractClassName: null,
        memberUserId: null,
        memberUserName: null,
        contractName: null,
        contractPrice: null,
        archiveLocation: null,
        isOriginal: '0',
        lackReason: null,
        annexUrl: null,
        warehousingTotal: null,
        warehousingTime: null,
        content: null,
        status: "0",
        sort: null,
        createAt: null,
        updateAt: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.showSearch = false
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        dateRange: [],
        resId: null,
        resName: null,
        resType: null,
        departmentContractNumber: null,
        contractNumber: null,
        signingTime: null,
        endTime: null,
        demandingSide: null,
        supplier: null,
        deptId: null,
        deptName: null,
        companyClassId: null,
        affiliationDept: null,
        contractClassId: null,
        contractClassName: null,
        memberUserId: null,
        memberUserName: null,
        contractName: null,
        contractPrice: null,
        archiveLocation: null,
        isOriginal: null,
        lackReason: null,
        annexUrl: null,
        warehousingTotal: null,
        warehousingTime: null,
        content: null,
      },

        this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractDetailsId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同信息详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const contractDetailsId = row.contractDetailsId || this.ids
      getCsContractDetails(contractDetailsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同信息详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.contractDetailsId != null) {
            updateCsContractDetails(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCsContractDetails(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractDetailsIds = row.contractDetailsId || this.ids;
      this.$modal.confirm('是否确认删除合同信息详情编号为"' + contractDetailsIds + '"的数据项？').then(function () {
        return delCsContractDetails(contractDetailsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cs/csContractDetails/export', {
        ...this.queryParams
      }, `合同列表_${new Date().getTime()}.xlsx`)
    },
    handleExportTemplate() {
      this.download('/cs/csContractDetails/exportTemplate', {
        ...this.queryParams
      }, `合同列表模板_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>

<style scoped>
::v-deep .dialog1 {
  background-color: #F8F8F8;
}

.searchForm {
  width: 650px;
  padding: 20px;
  position: absolute;
  left: 200px;
  z-index: 100;
  background-color: #FFFFFF;
  border: 1px solid #777777;
}
</style>
