<template>
  <div class="salesContract">
    <div class="search">
      <div class="left" />
      <div class="right">
        <div>
          <el-input v-model="search.contractInfo" placeholder="销售合同编号/销售合同名称" />
        </div>
        <div>
          <el-select v-model="search.importerCertNo" placeholder="请选择进口商" clearable>
            <el-option
              v-for="item in commodityList"
              :key="item.entityName"
              :label="item.entityName"
              :value="item.entityNo"
            />
          </el-select>
        </div>
        <div>
          <el-select v-model="search.agencyCertNo" placeholder="请选择代理公司" clearable>
            <el-option
              v-for="item in platformList"
              :key="item.platformName"
              :label="item.platformName"
              :value="item.certNo"
            />
          </el-select>
        </div>
        <div>
          <el-select v-model="search.paymentWay" placeholder="请选择付款方式" clearable>
            <el-option
              v-for="item in constant.payment_way"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </div>
        <div>
          <el-select v-model="search.contractStatus" placeholder="请选择合同状态" clearable>
            <el-option
              v-for="item in constant.sales_contract_status"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </div>
        <div>
          <el-date-picker
            v-model="addDate"
            type="daterange"
            range-separator="至"
            start-placeholder="添加日期范围"
            end-placeholder="添加日期范围"
          />
        </div>
        <div class="right-btn">
          <el-button type="primary" @click="fetchData('search')">查询</el-button>
          <el-button type="primary" @click="addContract">添加合同</el-button>
        </div>
      </div>
    </div>
    <cy-comm-table
      ref="commTable"
      v-loading="loading"
      :columns="columns"
      :data="tableData"
      :count="count"
      parent-component="SalesContract"
    />
    <uploadDialog
      :visible="uploadDialogVisible"
      :contract-id="curContractId"
      @close="uploadDialogVisible = false"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  getSalesList,
  getMyEnterprise,
  getTradePlatform,
  getCommodityByEnterpriseId,
  downloadSaleContractFile
} from '@/api/myTrade/salesContract'
import { exportFile, formatMoney, codeChangeName } from '@/utils'
import uploadDialog from './components/uploadDialog.vue'

export default {
  name: 'SalesContract',
  components: {
    uploadDialog
  },
  data() {
    return {
      count: 0,
      search: {
        customerUserInfo: '',
        importerCertNo: '',
        agencyCertNo: '',
        paymentWay: '',
        contractStatus: ''
      },
      page: 1,
      size: 10,
      addDate: [],
      tableData: [],
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '销售合同编号',
          prop: 'contractNo',
          width: 120,
          showTooltip: true
        },
        {
          label: '销售合同名称',
          showTooltip: true,
          prop: 'contractName',
          width: 120
        },
        {
          label: '进口商名称',
          showTooltip: true,
          width: 120,
          prop: 'importerEnterpriseName'
        },
        {
          label: '合同金额',
          showTooltip: true,
          render: (h, row) => {
            return <div>{ formatMoney(row.contractAmount) }</div>
          }
        },
        {
          label: '付款方式',
          prop: 'paymentWay',
          showTooltip: true,
          render: (h, row) => {
            return <div> <el-tooltip class='item' effect='dark' content={codeChangeName(this.constant.payment_way, row.paymentWay, 'dictValue', 'dictLabel')} placement='top'>
              <div class='one-ellipsis'>
                {codeChangeName(this.constant.payment_way, row.paymentWay, 'dictValue', 'dictLabel')}
              </div>
            </el-tooltip></div>
          }
        },
        {
          label: '付款币种',
          showTooltip: true,
          prop: 'paymentCurrency'
        },
        {
          label: '结算账期（天）',
          width: 120,
          showTooltip: true,
          render: (h, row) => {
            return <div>{ row.settlementCycle }</div>
          }
        },
        {
          label: '目的港',
          prop: 'portDestination',
          showTooltip: true
        },
        {
          label: '是否使用标准合同模板',
          prop: 'templateType',
          showTooltip: true,
          width: 160,
          render: (h, row) => {
            return row.templateType === true ? '是' : '否'
          }
        },
        {
          label: '合同状态',
          showTooltip: true,
          render: (h, row) => {
            return this.getcContractStatus(row.contractStatus)
          }
        },
        {
          label: '添加时间',
          showTooltip: true,
          prop: 'gmtCreate'
        },
        {
          label: '操作',
          width: 200,
          render: (h, row) => {
            const btnList = [
              {
                msg: '编辑',
                icon: 'iconfont icon-a-Group8151',
                rowPower: ['1'],
                category: 'edit'
              },
              {
                msg: '上传合同',
                icon: 'iconfont icon-a-Group782',
                power: '',
                rowPower: ['3'],
                category: 'upload'
              },
              {
                msg: '下载合同',
                icon: 'iconfont icon-Union',
                power: '',
                rowPower: ['3'],
                category: 'download'
              },
              {
                msg: '详情',
                icon: 'iconfont icon-a-Group957',
                // rowPower: ['', null],
                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.category === 'download' ? 'font-size: 18px' : '' }
                      onClick={() => { this.handlerOperate(item.category, row) }}
                    ></i>
                  </span>
                </el-tooltip>
              )
            })
            return <div>{ options }</div>
          }
        }
      ],
      loading: false,
      platformList: [],
      commodityList: [],
      uploadDialogVisible: false,
      curContractId: ''
    }
  },
  computed: {
    ...mapGetters(['constant']),
    tablePower() {
      return ({ item, tab, row }) => {
        const { category, rowPower } = item
        if (category === 'edit' && rowPower) {
          if (rowPower.includes(row.contractStatus)) {
            return true
          }
          return false
        }
        if (['upload', 'download'].includes(category) && rowPower) {
          if (rowPower.includes(row.contractStatus)) {
            return true
          }
          return false
        }
        return true
      }
    }
  },
  created() {
    this.$store.dispatch('getConstant', ['payment_way', 'sales_contract_status'])
  },
  mounted() {
    this.fetchData()
    this.queryMyEnterprice()
    this.queryTradePlatform()
  },
  methods: {
    fetchData(type) {
      this.loading = true
      if (type === 'search') {
        this.page = 1
        this.size = 10
      }
      const params = {
        ...this.search,
        timeStart: this.addDate.length ? this.addDate[0] : '',
        timeEnd: this.addDate.length ? this.addDate[1] : '',
        page: this.page || 1,
        rows: this.size || 10
      }
      getSalesList(params).then(({ data }) => {
        this.loading = false
        this.tableData = data.rows
        this.count = Number(data.records)
      })
    },
    handlerOperate(type, row) {
      if (type === 'play') {
        this.$router.push({
          name: 'RepaymentPlay',
          params: {
            id: row.id
          }
        })
      } else if (type === 'edit') {
        this.$router.push({
          name: 'SalesContractEdit',
          query: {
            type: 'edit',
            id: row.id
          }
        })
      } else if (type === 'see') {
        this.$router.push({
          name: 'SalesContractDetail',
          query: {
            type: 'see',
            id: row.id
          }
        })
      } else if (type === 'download') {
        this.downloadSaleContract(row.id)
      } else if (type === 'upload') {
        this.uploadDialogVisible = true
        this.curContractId = row.id
      }
    },
    async downloadSaleContract(id) {
      const res = await downloadSaleContractFile({ contractId: id })

      if (res) {
        exportFile(res)
      }
    },
    addContract() {
      this.$router.push({
        name: 'SalesContractAdd',
        query: {
          type: 'add'
        }
      })
    },
    // 查询企业
    async queryMyEnterprice() {
      const res = await getMyEnterprise()

      if (res.success) {
        this.queryCommodityByEnterpriseId(res.data.customerId)
      }
    },
    // 查询贸易平台
    async queryTradePlatform() {
      const res = await getTradePlatform()

      if (res.success) {
        this.platformList = res.data
      }
    },
    // 根据企业id查询进口商
    async queryCommodityByEnterpriseId(id) {
      const res = await getCommodityByEnterpriseId({ userId: id })

      if (res.success) {
        this.commodityList = res.data
      }
    },
    getcContractStatus(status) {
      const map = {
        1: '草稿',
        2: '生效',
        3: '待上传',
        6: '已完成'
      }
      return map[status] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
    .salesContract {

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