<template>
  <section>
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item label="合同列表" class="toolbar_formitem_n1"></el-form-item>
        <!-- 合同编号/名称 -->
        <el-form-item>
          <div style="display: flex;align-items: center;height: 40px;">
            <el-input v-model="keyword" class="input-with-select" placeholder="请输入" clearable size="small">
              <el-select slot="prepend" v-model="searchField" placeholder="请选择" style="width:120px">
                <el-option label="合同名称" :value="0"></el-option>
                <el-option label="合同编号" :value="1"></el-option>
              </el-select>
              <el-button slot="append" @click="searchFilter" icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </el-form-item>
        <!-- 合同类型 -->
        <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">合同类型</span>
          <el-select v-model="typeName" style="width:120px;" placeholder="请选择" @change="searchFilter" size="small" clearable>
            <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">状态</span>
          <el-select v-model="status" style="width:120px;" placeholder="请选择" @change="searchFilter" size="small" clearable>
            <el-option v-for="item,index in statusList" :key="item.label" :label="item.label" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <!-- 创建时间 -->
        <el-form-item>
          <span style="margin-left:5px;margin-right:5px;color:#606266;">创建时间</span>
          <el-date-picker
            style="width:240px;"
            v-model="dateArray"
            type="daterange"
            size="small"
            range-separator="-"
            :start-placeholder="'区间'"
            :end-placeholder="'区间'"
            value-format="yyyy-MM-dd"
            clearable
            @change="searchFilter"
          ></el-date-picker>
        </el-form-item>

        <el-form-item style="float:right;">
          <el-dropdown>
            <el-link type="primary" :underline="false">查看更多<i class="el-icon-arrow-down el-icon--right"></i></el-link>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="permissions.contractType"><el-link type="primary" :underline="false" @click="typeEdit()">类型编辑</el-link></el-dropdown-item>
              <el-dropdown-item v-if="permissions.contractImport"><el-link type="primary" :underline="false" @click="importDialog = true">导入</el-link></el-dropdown-item>
              <el-dropdown-item v-if="permissions.contractExport"><el-link type="primary" :underline="false" @click="exportContract()">导出</el-link></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item style="float:right;" v-if="permissions.contractNew">
          <el-link type="primary" :underline="false" @click="newlyAdd()">新增合同</el-link>
        </el-form-item>
      </el-form>
    </el-col>

    <el-table :data="contractList" v-loading="listLoading" :height="tableHeight" border highlight-current-row>
      <el-table-column prop="number" label="合同编号" min-width="150"></el-table-column>
      <el-table-column prop="name" label="合同名称" min-width="150"></el-table-column>
      <el-table-column prop="amounts" label="合同金额" min-width="150"></el-table-column>
      <el-table-column prop="typeName" label="合同类型" min-width="150"></el-table-column>
      <el-table-column prop="status" label="状态" min-width="150">
        <template slot-scope="scope">
          <span :style="statusList[scope.row.status].color">{{statusList[scope.row.status].label}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="indate" label="创建时间" min-width="150"></el-table-column>
      <el-table-column width="300" label="操作" align="left" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="permissions.contractView || permissions.contractManagement" size="mini" @click="lookover(scope.row)">查看</el-button>
          <el-button v-if="permissions.contractManagement" size="mini" @click="editContract(scope.row)" type="primary">编辑</el-button>
          <el-button v-if="permissions.contractAudit && (scope.row.status == 1 || scope.row.status == 3)" size="mini" @click="process(scope.row,0)" type="success">通过</el-button>
          <el-button v-if="permissions.contractAudit && (scope.row.status == 1 || scope.row.status == 3)" size="mini" @click="process(scope.row,2)" type="danger">驳回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-col :span="24" class="toolbar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[20 , 50 , 80 , 100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next"
        :total="total"
        style="float:right;"
      ></el-pagination>
    </el-col>

    <el-dialog :title="dialogTitle + '合同'" :visible.sync="addDialog" v-if="addDialog" :close-on-click-modal="false" customClass="customWidth" width="900px">
      <div style="height: 72vh;overflow-y: auto;overflow-x: hidden;">
        <el-form ref="contractForm" :model="contractForm" :rules="rules" label-width="120px" class="contractForm">
          <el-form-item label="合同编号">
            <el-input v-model="contractForm.number" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item label="合同名称" prop='name'>
            <el-input v-model="contractForm.name" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item label="合同金额">
            <el-input v-model="contractForm.amounts" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item label="合同类型">
            <el-select v-model="contractForm.typeId" placeholder="请选择" style="width:100%">
              <el-option v-for="item in typeList" :key="item.id" :label="item.typeName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计划开始时间">
            <el-date-picker
              v-model="contractForm.startDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
            <span style="float:right;">计划结束时间
            <el-date-picker
              style="margin-left: 15px;"
              v-model="contractForm.endDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
            </span>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="contractForm.remarks" placeholder="请输入" type="textarea" :rows="3" clearable></el-input>
          </el-form-item>
          <el-form-item label-width="0" class="contractFiles">
            <div class="contractFiles_title">附件
              <el-upload style="float:right;margin-right:5%;" ref="uploadFile" action="#" :http-request="httpRequest" :on-change="fileChange" :auto-upload="false" :show-file-list="false">
                <el-link type="primary">新增附件</el-link>
              </el-upload>
            </div>
            
            <el-table :data="fileList" :header-cell-style="{'font-weight':'normal'}" highlight-current-row
              max-height="240" style="width: 100%;margin-top:10px;margin-bottom:15px">
              <el-table-column label="序号" min-width="40" align="center">
                <template slot-scope="scope">
                  <div>{{scope.$index + 1}}</div>
                </template>
              </el-table-column>
              <el-table-column label="文件名称" prop="name" min-width="140"></el-table-column>
              <!-- <el-table-column label="文件大小" min-width="60">
                <template slot-scope="scope">
                  <div>{{scope.$index + 1}}</div>
                </template>
              </el-table-column> -->
              <el-table-column label="操作" min-width="40">
                <template slot-scope="scope">
                  <el-link @click="fileDelete(scope.row)" type="primary">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer;">
        <el-button @click.native="deleteContract()" style="float:left" v-if="dialogTitle == '编辑'">删除</el-button>
        <el-button @click.native="addDialog = false">取消</el-button>
        <el-button type="primary" @click="submitInsert()" :loading="submitLoading">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看合同" :visible.sync="lookoverDialog" v-if="lookoverDialog" :close-on-click-modal="false" customClass="customWidth" width="900px">
      <div style="height: 72vh;overflow-y: auto;overflow-x: hidden;">
        <el-form label-width="100px" class="lookoverContract clearfix">
          <el-form-item label="合同编号">
            {{contractForm.number}}
          </el-form-item>
          <el-form-item label="合同名称">
            {{contractForm.name}}
          </el-form-item>
          <el-form-item label="合同金额">
            {{contractForm.amounts}}
          </el-form-item>
          <el-form-item label="合同类型">
            {{contractForm.typeName}}
          </el-form-item>
          <el-form-item label="状态">
            {{statusList[contractForm.status].label}}
          </el-form-item>
          <el-form-item label="创建人">
            <span v-if="user.userNameNeedTranslate == 1"><ww-open-data type='userName' :openid='contractForm.creatorName'></ww-open-data></span>
            <span v-else>{{contractForm.creatorName}}</span>
          </el-form-item>
          <el-form-item label="创建时间">
            {{contractForm.indate}}
          </el-form-item>
          <el-form-item label="计划开始时间">
            {{contractForm.startDate}}
          </el-form-item>
          <el-form-item label="计划结束时间">
            {{contractForm.endDate}}
          </el-form-item>
          <el-form-item label="备注">
            {{contractForm.remarks}}
          </el-form-item>
          <el-form-item label-width="0" class="contractFiles">
            <div class="contractFiles_title">附件</div>
            <el-table :data="fileList" :header-cell-style="{'font-weight':'normal'}" highlight-current-row
              max-height="240" style="width: 100%;margin-top:10px;margin-bottom:30px">
              <el-table-column label="序号" min-width="40" align="center">
                <template slot-scope="scope">
                  <div>{{scope.$index + 1}}</div>
                </template>
              </el-table-column>
              <el-table-column label="文件名称" prop="name" min-width="140"></el-table-column>
              <!-- <el-table-column label="文件大小" min-width="60">
                <template slot-scope="scope">
                  <div>{{scope.$index + 1}}</div>
                </template>
              </el-table-column> -->
              <el-table-column label="操作" min-width="40">
                <template slot-scope="scope">
                  <el-link @click="fileDownload(scope.row)" type="primary">下载</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog title="合同类型管理" :visible.sync="typeDialog" v-if="typeDialog" customClass="customWidth" width="500px">
      <el-table :data="typeList" highlight-current-row  height="400" style="width: 100%;">
        <el-table-column type="index" width="60" label="序号">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="typeName"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="typeItemEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="typeItemDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer;">
        <el-button type="primary" @click="typeDialog = false">关闭</el-button>
        <el-button type="primary" @click="typeItemAdd()">新增合同类型</el-button>
      </div>
      <el-dialog :title="typeTitle + '合同类型'" :visible.sync="typeItemDialog" v-if="typeItemDialog" append-to-body width="400px">
        <div style="height: 12vh;overflow-y: auto;overflow-x: hidden;">
          <el-input v-model="typeItemForm.typeName"></el-input>
        </div>
        <div slot="footer" class="dialog-footer;">
          <el-button type="primary" @click="typeItemDialog = false">取消</el-button>
          <el-button type="primary" @click="typeItemSubmit()">确定</el-button>
        </div>
      </el-dialog>
    </el-dialog>

    <el-dialog title="导入合同" :visible.sync="importDialog" v-if="importDialog" width="30%">
      <!-- 模板？ -->
      <div slot="footer" class="dialog-footer" style="text-algin:center;">
        <el-upload ref="upload" action="#" :limit="1" :http-request="importContract" :show-file-list="false">
          <el-button type="primary" size="small" :loading="importLoading">导入合同</el-button>
        </el-upload>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      user: JSON.parse(sessionStorage.getItem("user")),
      permissions: JSON.parse(sessionStorage.getItem("permissions")),
      searchField: 0,
      keyword: '',
      typeName: '',
      status: '',
      dateArray: [],

      typeList: [],
      contractList: [],
      listLoading: false,
      statusList: [
        {label:'审核通过',color: 'color:#67c23a;'},
        {label:'待审核',color: 'color:#e6a23c;'},
        {label:'已驳回',color: 'color:#f56c6c;'},
        {label:'导入待审核',color: 'color:#e6a23c;'},
      ],
      typeDialog: false,
      typeTitle: '新增',
      typeItemDialog: false,
      typeItemForm: {typeName: ''},

      dialogTitle: '新增',
      addDialog: false,
      lookoverDialog: false,
      submitLoading: false,
      contractForm: {
        number: '',
        name: '',
        amounts: '',
        typeId: null,
        remarks: '',
        startDate: '',
        endDate: ''
      },
      rules:{
        name: [{ required: true, message: '请输入名称', trigger: "blur" }],
      },

      fileList: [],

      importDialog: false,
      importLoading: false,

      page: 1,
      size: 20,
      total: 0,
      tableHeight: 0
    }
  },
  created() {
    let height = window.innerHeight;
    this.tableHeight = height - 180;
    const that = this;
    window.onresize = function temp() {
      that.tableHeight = window.innerHeight - 185;
    };
  },
  mounted() {
    this.getContractList()
    this.getContractType()
  },
  methods: {
    test(row){
      console.log('test',row);
      // this.$refs.uploadFile.submit()
    },

    searchFilter(){
      this.page = 1
      this.getContractList()
    },
    handleSizeChange(val){
      this.size = val
      this.page = 1
      this.getContractList()
    },
    handleCurrentChange(val){
      this.page = val;
      this.getContractList()
    },

    importContract(item){
      let str = item.file.name.split('.')
      let format = str[str.length - 1];
      if(format != "xls" && format != "xlsx"){
        this.$message({
          message: '请选择.xls或.xlsx文件',
          type: 'error'
        })
      }else{
        this.importLoading = true
        let formData = new FormData();
        formData.append("file", item.file);
        formData.append("userId", this.user.id);
        this.http.uploadFile('/contract/importContract',formData,
        res => {
          this.$refs.upload.clearFiles();
          this.importLoading = false;
          if(res.code == 'ok'){
            this.importDialog = false
            this.$message({
              message: '导入成功',
              type: 'success'
            })
            this.getContractList()
          }else{
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },err => {
          this.importLoading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        })
      }
    },
    exportContract(){
      let parameter = {}
      if(this.typeName){
        parameter.typeName = this.typeName
      }
      if(this.keyword){
        if(this.searchField){
          parameter.number = this.keyword
        }else{
          parameter.name = this.keyword
        }
      }
      if(this.status !== ''){
        parameter.status = this.status
      }
      if(this.dateArray && this.dateArray.length == 2){
        parameter.startDate = this.dateArray[0]
        parameter.endDate = this.dateArray[1]
      }
      this.http.post('/contract/ExportContract',parameter,
      res => {
        if(res.code == 'ok'){
          let filePath = res.data;
          const a = document.createElement('a'); // 创建a标签
          a.setAttribute('download', '合同导出' + '.xls');// download属性
          a.setAttribute('href', filePath);// href链接
          a.click(); //自执行点击事件
          a.remove();
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },

    typeEdit(){
      this.typeDialog = true
    },
    typeItemAdd(){
      this.typeTitle = '新增'
      this.typeItemForm = {typeName: ''}
      this.typeItemDialog = true
    },
    typeItemEdit(row){
      this.typeTitle = '编辑'
      this.typeItemForm = JSON.parse(JSON.stringify(row))
      this.typeItemDialog = true
    },
    typeItemDelete(row){
      this.$confirm('确定要删除此条合同类型吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.http.post('/contractType/deleteContractType',{
          deleteId: row.id
        },res => {
          if(res.code == 'ok'){
            this.getContractType()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else{
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        },err => {
          this.$message({
            type: 'error',
            message: err
          });
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    typeItemSubmit(){
      this.http.post('/contractType/changeContractType',this.typeItemForm,
      res => {
        if(res.code == 'ok'){
          this.typeItemDialog = false
          this.getContractType()
          this.$message({
            message: this.typeTitle + '成功',
            type: 'success'
          })
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },


    newlyAdd(){
      this.dialogTitle = '新增'
      this.contractForm = {
        number: '',
        name: '',
        amounts: '',
        typeId: null,
        remarks: '',
        startDate: '',
        endDate: ''
      }
      this.fileList = []
      this.addDialog = true
    },
    editContract(row){
      this.dialogTitle = '编辑'
      this.contractForm = JSON.parse(JSON.stringify(row))
      this.fileList = this.contractForm.files ? this.contractForm.files : []
      for(let i in this.fileList){
        this.fileList[i].name = this.fileList[i].documentName
      }
      this.addDialog = true
    },
    deleteContract(){
      this.$confirm('确定要删除该合同吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.http.post('/contract/deleteContract',{
          id: this.contractForm.id
        },res => {
          if(res.code == 'ok'){
            this.addDialog = false
            this.getContractList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else{
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        },err => {
          this.$message({
            type: 'error',
            message: err
          });
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    process(row,status){
      this.http.post('/contract/processContract',{
        id: row.id,
        status: status
      },res => {
        if(res.code == 'ok'){
          row.status = status
          this.$message({
            message: status == 0 ? '已通过' : '已驳回',
            type: 'success'
          })
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    lookover(row){
      console.log('lookover',row);
      this.contractForm = row
      this.fileList = this.contractForm.files ? this.contractForm.files : []
      for(let i in this.fileList){
        this.fileList[i].name = this.fileList[i].documentName
      }
      this.lookoverDialog = true
    },
    submitInsert(){
      this.$refs.contractForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          delete this.contractForm.files
          this.http.post(this.dialogTitle == '新增' ? '/contract/addContract' : '/contract/editContract',this.contractForm,
          res => {
            this.submitLoading = false
            this.addDialog = false
            if(res.code == 'ok'){
              this.$message({
                message: res.msg,
                type: 'success'
              })
              if(this.dialogTitle == '新增'){
                this.contractForm.id = res.data
              }
              this.submitFile()
              
            }else{
              this.$message({
                message: res.msg,
                type: 'error'
              })
            }
          },err => {
            this.submitLoading = false
            this.addDialog = false
            this.$message({
              message: err,
              type: 'error'
            })
          })
        }
      })
    },

    fileChange(file,fileList){
      // console.log('fileChange',file,fileList);
      file.needUpload = true
      this.fileList.push(file)
    },
    fileDelete(row){
      console.log(row,this.fileList);
      this.$confirm('确定要删除该文件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(row.uid){
          for(let i in this.fileList){
            if(this.fileList[i].uid && this.fileList[i].uid == row.uid){
              this.fileList.splice(i,1)
            }
          }
        }else{
          this.http.post('/contract-document/fileDelete',{
            contractId: this.contractForm.id,
            fileIds: [row.id]
          },res => {
            if(res.code == 'ok'){
              this.getContractList()
              this.fileList.filter(item => !item.id || item.id != row.id)
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }else{
              this.$message({
                type: 'error',
                message: res.msg
              });
            }
          },err => {
            this.$message({
              type: 'error',
              message: err
            });
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    fileDownload(row){
      this.http.downloadFile('/contract-document/fileDown',{
        contractId: this.contractForm.id,
        fileId: row.id
      },row.name,err=>{
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    submitFile(){
      console.log('submitFile',this.fileList);
      let formData = new FormData();
      for(let i in this.fileList){
        if(this.fileList[i].needUpload){
          formData.append("file", this.fileList[i].raw);
        }
      }
      formData.append("ContractId", this.contractForm.id);
      this.http.uploadFile('/contract-document/fileUpload',formData,
      res => {
        if(res.code == 'ok'){
          this.getContractList()
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },


    getContractType(){
      this.http.post('/contractType/getContractType',{},
      res=>{
        if(res.code=='ok'){
          this.typeList = res.data
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err=>{
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    getContractList(){
      
      // pageIndex，pageSize，number，name，typeName，status，startDate，endDate
      let parameter = {
        pageIndex: this.page,
        pageSize: this.size,
      }
      if(this.typeName){
        parameter.typeName = this.typeName
      }
      if(this.keyword){
        if(this.searchField){
          parameter.number = this.keyword
        }else{
          parameter.name = this.keyword
        }
      }
      if(this.status !== ''){
        parameter.status = this.status
      }
      if(this.dateArray && this.dateArray.length == 2){
        parameter.startDate = this.dateArray[0]
        parameter.endDate = this.dateArray[1]
      }
      this.listLoading = true
      this.http.post('/contract/getContractPage',parameter,
      res => {
        this.listLoading = false
        if(res.code == 'ok'){
          this.contractList = res.data.data
          this.total = res.data.total
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      },err => {
        this.listLoading = false
        this.$message({
          message: err,
          type: 'error'
        })
      })
    }
  },
}
</script>

<style>
.lookoverContract{
  margin-top: 30px;
}
.lookoverContract .el-form-item{
  width: 50%;
  float: left;
}
.lookoverContract .el-form-item__label{
  font-weight: 600;
}
.lookoverContract .contractFiles{
  width: 100%;
}
.lookoverContract .contractFiles_title{
  margin-left: 5%;
  font-size: 16px;
  line-height: 20px;
  margin-top: 16px;
}
.contractForm{
  margin-top: 30px;
}
.contractForm .el-form-item{
  width: 90%;
}
.contractForm .contractFiles{
  width: 100%;
}
.contractForm .contractFiles_title{
  margin-left: 5%;
  font-size: 16px;
  line-height: 20px;
  margin-top: 16px;
}
</style>