<template>
  <div class="trade-relations-main">
    <div class="search">
      <div class="left" />
      <div class="right">
        <div>
          <el-input v-model="search.contractInfo" placeholder="采购合同编号/采购合同名称" />
        </div>
        <div v-if="enterpriseInfo.exportType == 'self_export' && enterpriseInfo.enterpriseType !== '1' && enterpriseInfo.enterpriseType !== '2'">
          <el-select v-model="search.vendorEntityNo" placeholder="请选择供应商" clearable>
            <el-option
              v-for="item in supplierList"
              :key="item.entityNo"
              :label="item.entityName"
              :value="item.entityNo"
            />
          </el-select>
        </div>
        <div v-if="enterpriseInfo.exportType === 'proxy_export'">
          <el-select v-model="search.agencyCertNo" placeholder="请选择代理公司" clearable>
            <el-option
              v-for="item in tradePlatformList"
              :key="item.certNo"
              :label="item.platformName"
              :value="item.certNo"
            />
          </el-select>
        </div>
        <div>
          <el-select v-model="search.contractStatus" placeholder="请选择合同状态" clearable>
            <el-option
              v-for="item in constant.purchase_contract_status"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </div>
        <div>
          <el-input v-model="search.salesContractNo" placeholder="相关销售合同编号" />
        </div>
        <div>
          <el-date-picker
            v-model="addDate"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="添加日期范围"
            end-placeholder="添加日期范围"
          />
        </div>
        <div class="right-btn">
          <el-button type="primary" @click="fetchData('search')">查询</el-button>
        </div>
      </div>
    </div>
    <cy-comm-table
      ref="commTable"
      v-loading="loading"
      :columns="columns"
      :data="tableData"
      :count="count"
      parent-component="PurchaseContract"
    />

    <cy-dialog ref="editDialog" title="上传合同" :width="'600px'" :top="'13vh'">
      <contract-upload v-if="showUpload" ref="contractUpload" />
      <div class="submit-btn" style="margin: 20px 0;">
        <el-button style="width: 150px;" @click="() => { $refs.editDialog.show = false;showUpload=false }">取消</el-button>
        <el-button type="primary" style="width: 150px;" @click="handleUpload">确定</el-button>
      </div>
    </cy-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import store from '@/store'
import { handleMoney, codeChangeName, parseTime } from '@/utils'
import { getPurchaseList, purchaseUpload } from '@/api/myTrade/purchaseContract'
import { getSupplierList, getTradePlatform } from '@/api/myTrade/salesContract'
import ContractUpload from './components/ContractUpload.vue'
export default {
  name: 'PurchaseContract',
  components: { ContractUpload },
  data() {
    return {
      count: 0,
      search: {
        contractInfo: '',
        contractStatus: '',
        vendorEntityNo: '',
        agencyCertNo: '',
        salesContractNo: ''
      },
      page: 1,
      size: 10,
      tableData: [],
      addDate: [],
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '采购合同编号',
          prop: 'contractNo',
          showTooltip: true
        },
        {
          label: '采购合同名称',
          showTooltip: true,
          prop: 'contractName'
        },
        {
          label: '供应商名称',
          prop: 'vendorEntityName',
          showTooltip: true
        },
        {
          label: '代理公司名称',
          prop: 'agencyEnterpriseName',
          showTooltip: true
        },
        {
          label: '合同金额',
          prop: 'contractAmount',
          showTooltip: true,
          render: (h, row) => {
            return <div> <el-tooltip class='item' effect='dark' content={'￥ ' + handleMoney(row.contractAmount)} placement='top'>
              <div class='one-ellipsis'>
                {'￥ ' + handleMoney(row.contractAmount)}
              </div>
            </el-tooltip></div>
          }
        },
        {
          label: '结算账期',
          prop: 'settlementCycle',
          showTooltip: true,
          render: (h, row) => {
            return <div> <el-tooltip class='item' effect='dark' content={(row.settlementCycle ? row.settlementCycle + '天' : '')} placement='top'>
              <div class='one-ellipsis'>
                {(row.settlementCycle ? row.settlementCycle + '天' : '')}
              </div>
            </el-tooltip></div>
          }
        },
        {
          label: '相关销售合同编号',
          prop: 'salesContractNo',
          showTooltip: true
        },
        {
          label: '是否使用标准合同模板',
          prop: 'templateType',
          showTooltip: true,
          render: (h, row) => {
            return row.templateType === true ? '是' : '否'
          }
        },
        {
          label: '合同状态',
          prop: 'status',
          showTooltip: true,
          render: (h, row) => {
            return <div> <el-tooltip class='item' effect='dark' content={codeChangeName(this.constant.purchase_contract_status, row.status, 'dictValue', 'dictLabel')} placement='top'>
              <div class='one-ellipsis'>
                {codeChangeName(this.constant.purchase_contract_status, row.status, 'dictValue', 'dictLabel')}
              </div>
            </el-tooltip></div>
          }
        },
        {
          label: '添加时间',
          prop: 'gmtCreate',
          showTooltip: true,
          render: (h, row) => {
            return <div> <el-tooltip class='item' effect='dark' content={parseTime(row.gmtCreate)} placement='top'>
              <div class='one-ellipsis'>
                {(parseTime(row.gmtCreate))}
              </div>
            </el-tooltip></div>
          }
        },
        {
          label: '操作',
          width: 150,
          render: (h, row) => {
            const btnList = [
              {
                msg: '编辑',
                icon: 'iconfont icon-a-Group8151',
                rowPower: ['0'],
                power: 'projectNumber:delete',
                category: 'edit'
              },
              { msg: '上传合同', icon: 'iconfont icon-orange icon-a-Group782', rowPower: ['1'], category: 'upload' },
              {
                msg: '下载合同',
                icon: 'iconfont icon-orange icon-Union',
                rowPower: ['1', '2', '3', '4'],
                style: 'display: inline-block; transform: scale(0.65)',
                category: 'download'
              },
              {
                msg: '详情',
                icon: 'iconfont icon-a-Group957',
                power: '',
                // rowPower: [4],
                category: 'see'
              }

            ]
            const options = btnList.map(item => {
              return (
                this.tablePower({ item, row }) && <el-tooltip class='item' effect='dark' content={item.msg} placement='top'>
                  <span class='table-icon-box'>
                    <i class={item.icon} style={item.style} onClick={() => { this.handlerOperate(item.category, row) }}></i>
                  </span>
                </el-tooltip>
              )
            })
            return <div>{ options }</div>
          }
        }
      ],
      loading: false,

      supplierList: [],
      tradePlatformList: [],
      uploadId: null,
      showUpload: false

    }
  },
  computed: {
    ...mapGetters(['constant', 'enterpriseInfo']),
    tablePower() {
      return ({ item, row }) => {
        const { rowPower } = item
        if (rowPower) {
          if (rowPower.includes(row.status)) {
            return true
          }
        } else {
          return true
        }
      }
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['purchase_contract_status'])
    this.getSupplier()
    this.getPlatList()

    // 代理出口 || 内资生产企业 外商投资生产企业 --无供应商列
    if (this.enterpriseInfo.exportType === 'proxy_export' || (this.enterpriseInfo.exportType === 'self_export' && ['1', '2'].includes(this.enterpriseInfo.enterpriseType))) {
      this.columns = this.columns.slice().filter(el => el.label !== '供应商名称')
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    fetchData(type) {
      this.loading = true
      if (type === 'search') {
        this.page = 1
        this.size = 10
      }
      const params = {
        ...this.search,
        gmtCreateStart: this.addDate && this.addDate.length ? this.addDate[0] + ' 00:00:00' : '',
        gmtCreateEnd: this.addDate && this.addDate.length ? this.addDate[1] + ' 23:59:59' : '',
        page: this.page || 1,
        rows: this.size || 10
      }
      getPurchaseList(params).then(({ data }) => {
        this.loading = false
        this.tableData = data.rows
        this.count = Number(data.records)
      })
    },
    handlerOperate(type, row) {
      if (type === 'edit') {
        this.$router.push({
          name: 'PurchaseContractEdit',
          query: {
            type: 'edit',
            id: row.id
          }
        })
      } else if (type === 'see') {
        this.$router.push({
          name: 'PurchaseContractView',
          query: {
            type: 'view',
            id: row.id
          }
        })
      } else if (type === 'upload') {
        this.uploadId = row.id
        this.$refs.editDialog.show = true
        this.showUpload = true
      } else if (type === 'download') {
        if (row.purchaseContractFile && row.purchaseContractFile.id) {
          this.purchaseDownload(row.purchaseContractFile.id)
        }
      }
    },

    getSupplier() {
      const userId = store.getters.userInfo.id
      getSupplierList({ userId: userId }).then(res => {
        this.supplierList = res.data || []
      })
    },
    getPlatList() {
      getTradePlatform().then(res => {
        this.tradePlatformList = res.data || []
      })
    },
    async handleUpload() {
      const uploadData = await this.$refs.contractUpload.getParams()
      uploadData.contractId = this.uploadId
      uploadData.Loading = true
      purchaseUpload(uploadData).then(res => {
        this.$message.success('上传成功')
        this.showUpload = false
        this.$refs.editDialog.show = false
        this.fetchData()
      })
    },
    async purchaseDownload(val) {
      if (val) {
        const idNum = val
        window.open(`${process.env.VUE_APP_BASE_API}/file_storage_oss/download/${idNum}`)
      }
    }

  }
}
</script>

  <style lang="scss" scoped>
      .financing-main {

      }
  </style>
  <style lang="scss">
      .financing-main {
          .icon-a-Group957, .icon-a-Group1087 {
              font-size: 28px;
          }
      }
  </style>
