<template>
  <div class="basic-content">
    <el-tabs v-model="step" type="card">
      <el-tab-pane label="基础内容" :name="'first'" />
      <el-tab-pane label="合同条款" :name="'second'" />
    </el-tabs>
    <p style="text-align: right;">
      <span style="margin-right: 15px;">{{ codeToName(constant.purchase_contract_status, status, 'dictValue', 'dictLabel' ) }}</span>
    </p>

    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
      label-width="150px"
      class="rule-form-orange"
    >

      <div v-show="step === 'first'" style="display: flex; width: 100%;flex-wrap: wrap;">
        <cy-info-title>基础信息</cy-info-title>
        <el-form-item
          label="是否使用标准合同模版"
          prop="templateType"
        >
          <el-select
            v-model="ruleForm.templateType"
            placeholder="请选择是否使用标准合同模版"
            :disabled="disabled"
          >
            <el-option
              v-for="item in constant.sys_yes_no"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购合同编号" prop="contractNo" :rules="[{ required: ruleForm.templateType === 'N', message: '请输入合同编号', trigger: 'blur' }]">
          <el-input
            v-model="ruleForm.contractNo"
            placeholder="请输入采购合同编号"
            :disabled="disabled || ruleForm.templateType === 'Y'"
          />
        </el-form-item>
        <el-form-item label="采购合同名称" prop="contractName" :rules="[{ required: true, message: `请输入合同名称`, trigger: 'blur' }]">
          <el-input
            v-model="ruleForm.contractName"
            placeholder="请输入采购合同名称"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item v-if="ruleForm.exportType == 'self_export' && enterpriseInfo.enterpriseType !== '1' && enterpriseInfo.enterpriseType !== '2'" label="供应商名称" prop="vendorEntityName">
          <el-input
            :value="ruleForm.vendorEntityName || '--'"
            disabled
          />
        </el-form-item>
        <el-form-item label="相关销售合同编号" prop="salesContractNo">
          <el-input
            v-model="ruleForm.salesContractNo"
            disabled
          />
        </el-form-item>
        <el-form-item v-if="ruleForm.exportType === 'proxy_export'" label="代理公司名称" prop="agencyEnterpriseName">
          <el-input
            :value="ruleForm.agencyEnterpriseName"
            disabled
          />
        </el-form-item>

        <el-form-item v-if="status === 4" label="采购合同" prop="purchaseContractFile">
          <span slot="label" class="required-label">采购合同</span>
          <cy-upload
            ref="purchaseContractFile"
            :upload-params="{
              fileType: 'purchaseContractFile'
            }"
            :file-data="ruleForm.purchaseContractFile"
            :upload-from-orange-status="true"
            :file-type="'pdf'"
            placeholder="请上传采购合同"
            :limit="1"
            :file-size="20"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item v-if="ruleForm.exportType === 'proxy_export' && ruleForm.proxyDistrictCode === 'CN_MAINLAND'" label="承诺函" prop="platformCommitmentLetter">
          <span slot="label" class="required-label">承诺函</span>
          <cy-upload
            ref="platformCommitmentLetter"
            :file-data="ruleForm.platformCommitmentLetter"
            :upload-from-orange-status="true"
            :file-type="'pdf'"
            :limit="1"
            :file-size="20"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item v-if="status === 4" label="签署日期" prop="signDate" :rules="[{ required: true, message: `请输选择签署日期`, trigger: 'change' }]">
          <el-date-picker v-model="ruleForm.signDate" value-format="yyyy-MM-dd" type="date" placeholder="选择签署日期" style="width: 100%;" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="合同金额">
          <el-input
            :value="ruleForm.contractAmount ? '￥ ' + formatMoney(ruleForm.contractAmount) : ''"
            disabled
          />
        </el-form-item>

        <cy-info-title style="margin-top: 15px;">商品信息</cy-info-title>
        <div style="width: 100%;margin: 0;">
          <cy-comm-table
            ref="commTable"
            :columns="columns"
            :data="goodsInfoList"
            :count="0"
          />
        </div>

        <cy-info-title style="margin-top: 15px;">其他信息</cy-info-title>
        <el-form-item label="更新人">
          <el-input
            :value="otherInfo.updateBy"
            disabled
          />
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input
            :value="otherInfo.gmtModified"
            disabled
          />
        </el-form-item>
      </div>

      <!-- 合同条款 -->
      <div v-show="step === 'second'" style="display: flex; width: 100%;flex-wrap: wrap;">
        <cy-info-title>付款</cy-info-title>
        <el-form-item label="结算账期">
          <el-input :value="ruleForm.contractTerms.settlementCycle + '天'" disabled />
        </el-form-item>
        <el-form-item label="发票类型" prop="contractTerms.invoiceType" :rules="[{ required: step === 'second', message: `请输选择发票类型`, trigger: 'change' }]">
          <el-select
            v-model="ruleForm.contractTerms.invoiceType"
            placeholder="请选择发票类型"
            :disabled="disabled"
          >
            <el-option
              v-for="item in constant.invoice_type"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <div style="width: 100%; margin-top: 15px;" class="table-box">
          <el-table :data="paymentInfo" style="width: 100%;">
            <el-table-column prop="paymentRatio" label="款项比例（%）">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.paymentRatio"
                  placeholder="请输入，例如：2.00"
                  :disabled="disabled"
                />
              </template>
            </el-table-column>
            <el-table-column prop="paymentName" label="款项名称">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.paymentName"
                  placeholder="请输入，例如：预付款"
                  :disabled="disabled"
                />
              </template>
            </el-table-column>
            <el-table-column prop="paymentTime" label="付款时点">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.paymentTime"
                  placeholder="请输入，例如：合同签署后"
                  :disabled="disabled"
                />
              </template>
            </el-table-column>
            <el-table-column prop="paymentTerm" label="付款期限">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.paymentTerm"
                  placeholder="请输入 (若为付款时点当天，则期限填为0) "
                  :disabled="disabled"
                >
                  <template slot="append">天</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column v-if="!disabled" label="操作" width="150">
              <template slot-scope="scope">
                <div style="cursor: pointer;">
                  <span style="margin-right:10px;color: #FE7D0B;" @click="addPayment()">新增</span>
                  <span v-if="paymentInfo && paymentInfo.length > 1" style="color: #FE7D0B;" @click="deletePayment(scope.$index)">删除</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <cy-info-title style="margin-top: 15px;">收款账户信息</cy-info-title>
        <el-form-item label="账户名称">
          <el-input :value="ruleForm.contractTerms.accountName" disabled />
        </el-form-item>
        <el-form-item label="银行账号">
          <el-input :value="ruleForm.contractTerms.accountNumber" disabled />
        </el-form-item>
        <el-form-item label="开户行">
          <el-input :value="ruleForm.contractTerms.openingBank" disabled />
        </el-form-item>

        <cy-info-title style="margin-top: 15px;">特殊约定（选填）
          <div v-if="source !== 'view'" slot="right" style="display: flex; align-items: center;">
            <el-button type="text" @click="addTitle">添加</el-button>
          </div>
        </cy-info-title>
        <div style="width: 100%; margin-top: 15px;" class="table-box">
          <el-table :data="titleInfo" style="width: 100%;">
            <el-table-column prop="termTitle" label="条款标题" width="300">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.termTitle"
                  placeholder="请输入"
                  :disabled="disabled"
                />
              </template>
            </el-table-column>
            <el-table-column prop="content" label="条款内容">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.content"
                  placeholder="请输入"
                  :disabled="disabled"
                />
              </template>
            </el-table-column>
            <el-table-column v-if="!disabled" label="操作" width="60">
              <template slot-scope="scope">
                <div style="color: #FE7D0B; cursor: pointer;">
                  <span @click="deleteTitle( scope.$index)">删除</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <cy-info-title>备注（选填）</cy-info-title>
        <el-form-item label="备注" prop="contractTerms.remark">
          <el-input v-model="ruleForm.contractTerms.remark" :disabled="disabled" />
        </el-form-item>
      </div>
    </el-form>

    <div class="submit-btn">
      <el-button @click="() => { $router.push({name: 'PurchaseSalesContract'}) }">返回</el-button>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { handleMoney, codeChangeName } from '@/utils'
import { getMyEnterprise } from '@/api/myTrade/salesContract'
import { getContractDetail } from '@/api/myTrade/purchaseContract'
export default {
  props: {
    source: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      step: 'first',
      ruleForm: {
        id: '',
        exportType: '',
        proxyDistrictCode: '',
        customerUserId: '',
        customerIdentifierNo: '',
        customerEnterpriseName: '',
        templateType: '',
        contractNo: '',
        contractName: '',
        salesContractId: '',
        signDate: '',
        vendorEntityName: '',
        vendorEntityNo: '',
        salesContractNo: '',
        agencyEnterpriseName: '',
        agencyEnterpriseNo: '',
        contractAmount: '',
        purchaseContractFile: [],
        platformCommitmentLetter: [],

        contractTerms: {
          settlementCycle: '',
          invoiceType: '',
          accountName: '',
          accountNumber: '',
          openingBank: '',
          remark: ''
        }
      },
      paymentInfo: [
        {
          type: 1,
          paymentName: '',
          content: '',
          paymentTime: '',
          rate: ''
        }
      ],
      titleInfo: [
        {
          type: 2,
          termTitle: '',
          content: ''
        }
      ],
      otherInfo: {
        gmtModified: '',
        updateBy: ''
      },
      rules: {
        templateType: [
          { required: true, message: `请选择是否使用标准合同模板`, trigger: 'change' }
        ]

      },
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '商品名称',
          showTooltip: true,
          prop: 'name'
        },
        {
          label: '报关品名',
          showTooltip: true,
          prop: 'declarationName'
        },
        {
          label: '型号',
          showTooltip: true,
          prop: 'model'
        },
        {
          label: '申报计量单位',
          showTooltip: true,
          prop: 'measurementUnit'
        },
        {
          label: '包装规格',
          showTooltip: true,
          prop: 'packSpec'
        },
        {
          label: '数量',
          // showTooltip: true,
          prop: 'number'
        },
        {
          label: '采购单价 (不含税) (CNY)',
          showTooltip: true,
          prop: 'priceUnit',
          render: (h, row) => {
            return <div> <el-tooltip class='item' effect='dark' content={handleMoney(row.priceUnit)} placement='top'>
              <div class='one-ellipsis'>
                {handleMoney(row.priceUnit)}
              </div>
            </el-tooltip></div>
          }
        },
        {
          label: '增值税税率（%）',
          showTooltip: true,
          prop: 'addedTaxRate',
          render: (h, row) => {
            return <div> <el-tooltip class='item' effect='dark' content={Number(row.addedTaxRate) * 100} placement='top'>
              <div class='one-ellipsis'>
                {Number(row.addedTaxRate) * 100}
              </div>
            </el-tooltip></div>
          }
        },
        {
          label: '商品金额 (CNY)',
          showTooltip: true,
          prop: 'totalAmount',
          render: (h, row) => {
            return <div> <el-tooltip class='item' effect='dark' content={handleMoney(row.totalAmount)} placement='top'>
              <div class='one-ellipsis'>
                {handleMoney(row.totalAmount)}
              </div>
            </el-tooltip></div>
          }
        }
      ],

      status: null,
      goodsInfoList: [],
      disabled: false,

      contractList: [],
      ruleFormSign: {
        isSign: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'constant', 'enterpriseInfo'
    ])

  },
  created() {
    this.disabled = this.source !== 'edit'
    this.$store.dispatch('getConstant', ['sys_yes_no', 'invoice_type', 'purchase_contract_status'])
    // this.queryMyEnterprice()
    // this.getDetail()
    Promise.all([
      this.queryMyEnterprice()
    ]).then(results => {
      // if (!(results.filter(item => { return !item })).length) {
      this.getDetail()
      // }
    })
      .catch(error => { console.log(error) })
  },
  methods: {

    // 查询企业
    async queryMyEnterprice() {
      const res = await getMyEnterprise()
      // exportType proxy_export --代理 区域中国大陆+代理出口
      if (res.success) {
        if (res.data.proxyDistrictCode === 'CN_MAINLAND' && res.data.exportType === 'proxy_export') {
          this.ruleForm.templateType = 'Y'
        } else {
          this.ruleForm.templateType = 'N'
        }
        this.ruleForm.exportType = res.data.exportType
        this.ruleForm.proxyDistrictCode = res.data.proxyDistrictCode
        // this.queryCommodityByEnterpriseId(res.data.customerId)
      }
    },

    // 合同详情
    getDetail() {
      const { id } = this.$route.query
      getContractDetail(id).then(res => {
        const { data } = res
        this.ruleForm.id = data.id
        this.ruleForm.templateType = data.templateType ? 'Y' : 'N'
        this.ruleForm.customerUserId = data.customerUserId
        this.ruleForm.customerIdentifierNo = data.customerIdentifierNo
        this.ruleForm.customerEnterpriseName = data.customerEnterpriseName
        this.ruleForm.contractNo = data.contractNo
        this.ruleForm.contractName = data.contractName
        this.ruleForm.salesContractId = data.salesContractId
        this.ruleForm.vendorEntityName = data.vendorEntityName
        this.ruleForm.vendorEntityNo = data.vendorEntityNo
        this.ruleForm.salesContractNo = data.salesContractNo
        this.ruleForm.agencyEnterpriseName = data.agencyEnterpriseName
        this.ruleForm.agencyCertNo = data.agencyCertNo
        this.ruleForm.signDate = data.signDate
        this.ruleForm.contractAmount = data.contractAmount
        this.ruleForm.purchaseContractFile = data.purchaseContractFile && data.purchaseContractFile.id ? [data.purchaseContractFile] : []
        this.ruleForm.platformCommitmentLetter = data.platformCommitmentLetter && data.platformCommitmentLetter.id ? [data.platformCommitmentLetter] : []

        this.goodsInfoList = data.commodityList

        this.ruleForm.contractTerms = data.contractTerms

        this.paymentInfo = data.contractTerms.paymentInfo

        this.titleInfo = data.contractTerms.titleInfo ? data.contractTerms.titleInfo : []

        this.status = Number(data.status)
        this.otherInfo.gmtModified = data.gmtModified
        this.otherInfo.updateBy = data.updateBy
      })
    },
    priceUnitFeildsChang(val, row) {
      if (row.number !== '' || row.number !== null) {
        row.totalAmount = row.number * row.priceUnit
      }
    },

    codeToName(list, type, code, name) {
      return codeChangeName(list, type, code, name)
    },
    formatMoney(val) {
      if (val) {
        return handleMoney(val)
      } else {
        return 0.00
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.basic-content {
    padding: 10px 20px;
    .sales-order-step {
        width: 50%;
        margin: 0 auto 20px;
      }
}
</style>
