<template>
  <div class="basic-content">
    <el-steps :space="200" :active="step" simple class="sales-order-step">
      <el-step title="基础内容" />
      <el-step title="合同条款" />
    </el-steps>

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

      <div v-show="step === 0" 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="(ruleForm.templateType === 'N' && source === 'edit') || (source === 'view' && 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.templateType === 'N' && source === 'edit' ) || (source === 'view' && 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>

        <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>
      </div>

      <!-- 合同条款 -->
      <div v-show="step === 1" 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 === 1, 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="ruleForm.proxyDistrictCode === 'CN_MAINLAND' && ruleForm.exportType === 'proxy_export'"
                />
              </template>
            </el-table-column>
            <el-table-column prop="paymentName" label="款项名称">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.paymentName"
                  placeholder="请输入，例如：预付款"
                  :disabled="ruleForm.proxyDistrictCode === 'CN_MAINLAND' && ruleForm.exportType === 'proxy_export'"
                />
              </template>
            </el-table-column>
            <el-table-column prop="paymentTime" label="付款时点">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.paymentTime"
                  placeholder="请输入，例如：合同签署后"
                  :disabled="ruleForm.proxyDistrictCode === 'CN_MAINLAND' && ruleForm.exportType === 'proxy_export'"
                />
              </template>
            </el-table-column>
            <el-table-column prop="paymentTerm" label="付款期限">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.paymentTerm"
                  placeholder="请输入 (若为付款时点当天，则期限填为0) "
                  :disabled="ruleForm.proxyDistrictCode === 'CN_MAINLAND' && ruleForm.exportType === 'proxy_export'"
                >
                  <template slot="append">天</template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column v-if="!(ruleForm.proxyDistrictCode === 'CN_MAINLAND' && ruleForm.exportType === 'proxy_export')" 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="账户名称" prop="contractTerms.accountName" :rules="[{ required: ruleForm.exportType === 'proxy_export' && step === 1, message: `请输入`, trigger: 'blur' }]">
          <el-input v-model="ruleForm.contractTerms.accountName" :disabled="ruleForm.exportType === 'self_export'" />
        </el-form-item>
        <el-form-item label="银行账号" prop="contractTerms.accountNumber" :rules="[{ required: ruleForm.exportType === 'proxy_export' && step === 1, message: `请输入`, trigger: 'blur' },{ validator: validNumber,trigger: 'blur' }]">
          <el-input v-model="ruleForm.contractTerms.accountNumber" :disabled="ruleForm.exportType === 'self_export'" />
        </el-form-item>
        <el-form-item label="开户行" prop="contractTerms.openingBank" :rules="[{ required: ruleForm.exportType === 'proxy_export' && step === 1, message: `请输入`, trigger: 'blur' }]">
          <el-input v-model="ruleForm.contractTerms.openingBank" :disabled="ruleForm.exportType === 'self_export'" />
        </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>
      <el-button v-if="source !== 'view'" type="primary" @click="submitClick('save')">暂存</el-button>
      <el-button v-if="step === 1 && source !== 'view'" type="primary" @click="prevStep()">上一步</el-button>
      <el-button v-if="step === 0 && source !== 'view'" type="primary" @click="nextStep()">下一步</el-button>
      <el-button v-if="step === 1 && source !== 'view'" type="primary" @click="submitClick('submit')">提交</el-button>
    </div>

    <cy-dialog ref="editDialog" title="采购合同文件" :show-close="false">
      <div class="table-box">
        <el-table :data="contractList" style="width: 100%;">
          <el-table-column prop="content" label="生成的采购合同">
            <template slot-scope="{ row }">
              <span style="cursor: pointer;color: #5AC4FC;font-size: 14px;" @click="downloadContract(row)">{{ row.originalName }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-form
        ref="ruleFormSign"
        :model="ruleFormSign"
        label-position="top"
        label-width="150px"
        class="rule-form-orange list-form"
      >
        <el-form-item
          label="是否电子签"
          prop="isSign"
          :rules="[{required: true, message: `请选择`, trigger: 'change' }]"
        >
          <el-select
            v-model="ruleFormSign.isSign"
            placeholder="请选择是否电子签"
            :disabled="ruleForm.proxyDistrictCode === 'CN_MAINLAND' && ruleForm.exportType === 'proxy_export'"
          >
            <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>
      <div class="submit-btn" style="margin: 20px 0;">
        <!-- <el-button style="width: 150px;" @click="() => { $refs.editDialog.show = false;}">取消</el-button> -->
        <el-button type="primary" style="width: 150px;" @click="handleSign">确定</el-button>
      </div>
    </cy-dialog>
  </div>
</template>

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

        contractTerms: {
          settlementCycle: '',
          invoiceType: '',
          accountName: '',
          accountNumber: '',
          openingBank: '',
          remark: ''
        }
      },
      paymentInfo: [
        {
          type: 1,
          paymentRatio: '',
          paymentName: '',
          paymentTime: '',
          paymentTerm: ''
        }
      ],
      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 (
              <cy-amount-input
                v-model={ row.priceUnit }
                disabled={ this.ruleForm.proxyDistrictCode === 'CN_MAINLAND' && this.ruleForm.exportType === 'proxy_export' }
                onChange={ (val) => { this.priceUnitFeildsChang(val, row) } }
              ></cy-amount-input>
            )
          }
        },
        {
          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.$store.dispatch('getConstant', ['sys_yes_no', 'invoice_type', 'purchase_contract_status'])

    Promise.all([
      this.queryMyEnterprice()
    ]).then(results => {
      this.getDetail()
      // }
    })
      .catch(error => { console.log(error) })
  },
  methods: {

    async submitClick(type) {
      const postData = await this.validate(type)
      postData.templateType = postData.templateType === 'Y'
      if (postData) {
        const params = {
          operate: type
        }
        submitPurchaseContract(params, postData).then(res => {
          if (type === 'save') {
            this.$message.success('保存成功')
            this.$router.go(-1)
          } else {
            if (this.ruleForm.templateType === 'Y') {
              this.contractList = res.data
              this.$refs.editDialog.show = true

              if (this.ruleForm.proxyDistrictCode === 'CN_MAINLAND' && this.ruleForm.exportType === 'proxy_export') {
                this.ruleFormSign.isSign = 'Y'
              }
            } else {
              this.$message.success('提交成功')
              this.$router.go(-1)
            }
          }
        })
      }
    },

    // 上一步
    prevStep() {
      this.step = 0
    },

    // 下一步
    async nextStep() {
      await this.validate('submit')
      this.step = 1
    },

    async validate(type) {
      var params = {
        Loading: true,
        ...this.ruleForm
      }
      params.commodityList = this.goodsInfoList
      if (this.ruleForm.templateType === 'N') {
        const purchaseContractFile = this.$refs.purchaseContractFile.getFileLists
        params.purchaseContractFile = purchaseContractFile.length ? { id: purchaseContractFile.map(item => item.id)[0] } : null
      } else {
        params.purchaseContractFile = null
      }
      if (this.step === 1) {
        params.contractTerms.paymentInfo = this.paymentInfo
        params.contractTerms.titleInfo = this.titleInfo
      } else {
        params.contractTerms.paymentInfo = null
        params.contractTerms.titleInfo = null
      }

      return new Promise((resolve, reject) => {
        if (type === 'submit') {
          this.$refs.ruleFormRef.validate(valid => {
            if (valid) {
              if (this.ruleForm.templateType === 'N') {
                const purchaseContractFile = this.$refs.purchaseContractFile.getFileLists
                if (!purchaseContractFile.length) {
                  this.$message.warning('请上传采购合同')
                  return
                }
              }
              if (this.step === 2) {
                if (!this.validatePayInfo()) {
                  return
                }
                // 付款款项表格的款项比例之和必须为100，且表格最大值的付款期限必须等于结算账期
                if (this.paymentInfo.length > 0) {
                  const paymentRatioSum = this.paymentInfo.reduce((acc, cur) => acc + cur.paymentRatio, 0)

                  if (paymentRatioSum !== 100) {
                    this.$message.warning('付款款项表格的款项比例之和必须为100')
                    return
                  }

                  const maxPaymentRatio = Math.max(...this.paymentInfo.map(item => item.paymentRatio))

                  const find = this.paymentInfo.find(el => el.paymentRatio === maxPaymentRatio)

                  if (find && find.paymentTerm !== params.settlementCycle) {
                    this.$message.warning('付款款项表格款项比例最大值的付款期限必须等于结算账期')
                    return
                  }
                }
              }
              return resolve(params)
            } else {
              reject()
              return false
            }
          })
        } else {
          resolve(params)
        }
      })
    },

    handleSign() {
      this.$refs.ruleFormSign.validate(valid => {
        if (valid) {
          if (this.ruleFormSign.isSign === 'N') {
            this.$refs.editDialog.show = false
            this.$router.go(-1)
          } else {
            purchaseContractSign(this.ruleForm.id).then(res => {
              this.$message.success('提交成功')
              this.$refs.editDialog.show = false
              this.$router.go(-1)
            })
          }
        }
      })
    },

    downloadContract(val) {
      if (val.id) {
        const idNum = val.id
        window.open(`${process.env.VUE_APP_BASE_API}/file_storage_oss/preview/${idNum}?resource=1#toolbar=0&navpanes=0&scrollbar=0`)
      }
    },

    // 查询企业
    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.goodsInfoList = data.commodityList

        this.ruleForm.contractTerms = data.contractTerms

        console.log(data.contractTerms.paymentInfo, data.contractTerms.paymentInfo.length)
        this.paymentInfo = data.contractTerms.paymentInfo && data.contractTerms.paymentInfo.length !== 0 ? data.contractTerms.paymentInfo : this.paymentInfo

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

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

    validatePayInfo() {
      let i = 0
      while (i < this.paymentInfo.length) {
        if (!this.paymentInfo[i].paymentRatio) {
          this.$message.warning(`请输入付款条件列表第${i + 1}行款项比例`)
          return false
        }
        if (!this.paymentInfo[i].paymentTime) {
          this.$message.warning(`请输入付款条件列表第${i + 1}行付款时点`)
          return false
        }
        if (!this.paymentInfo[i].paymentRatio) {
          this.$message.warning(`请输入付款条件列表第${i + 1}行款项比例`)
          return false
        }
        if (this.paymentInfo[i].paymentTerm === '') {
          this.$message.warning(`请输入付款条件列表第${i + 1}行付款期限`)
          return false
        } else if (this.paymentInfo[i].paymentTerm !== '') {
          if (isNaN(this.paymentInfo[i].paymentTerm)) {
            this.$message.warning(`请输入付款条件列表第${i + 1}行付款期限必须为数字`)
            return false
          }
        }
        i++
      }
      return true
    },
    // 添加
    addPayment() {
      this.paymentInfo.push({
        type: 1,
        paymentRatio: '',
        paymentName: '',
        paymentTime: '',
        paymentTerm: ''
      })
    },
    deletePayment(index) {
      this.paymentInfo.splice(index, 1)
    },

    // 添加特殊约定
    addTitle() {
      this.titleInfo.push({
        type: 2,
        termTitle: '',
        content: ''
      })
    },
    deleteTitle(index) {
      this.titleInfo.splice(index, 1)
    },

    validNumber(rule, value, callback) {
      if (this.step === 1) {
        if (value === '') {
          callback(new Error('请输入'))
        } else if (!/^-?\d+(\.\d+)?$/.test(value)) {
          callback(new Error('格式有误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },

    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>
