<template>
  <div class="sales-order-edit">

    <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="importerId"
        >
          <el-select
            v-model="ruleForm.importerId"
            placeholder="请选择进口商名称"
            :disabled="editImporterDisabled"
            @change="importerChange"
          >
            <el-option
              v-for="item in importerList"
              :key="item.entityNo"
              :label="item.entityName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="销售合同名称"
          prop="saleContractId"
        >
          <el-select
            v-model="ruleForm.saleContractId"
            placeholder="请选择销售合同"
            :disabled="editContractDisabled"
            @change="salesChange"
          >
            <el-option
              v-for="item in salesContractList"
              :key="item.contractNo"
              :label="item.contractName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售合同编号" prop="salesContractNo">
          <el-input
            v-model="ruleForm.salesContractNo"
            disabled
          />
        </el-form-item>
        <el-form-item v-if="exportType === 'proxy_export'" label="代理公司名称" prop="agencyName">
          <el-input
            v-model="ruleForm.agencyName"
            disabled
          />
        </el-form-item>

        <cy-info-title style="margin-top: 20px;">商品信息
          <div slot="right" style="display: flex; align-items: center;">
            <el-input v-model="searchGoodsName" placeholder="报关品名" clearable>
              <template #append>
                <el-button slot="append" icon="el-icon-search" @click="getGoodsList" />
              </template>
            </el-input>
          </div>
        </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>
        <div style="width: 100%; margin-top: 15px;" class="table-box">
          <el-table :data="selectedGoods" style="width: 100%;">
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column v-if="enterpriseInfo.exportType == 'self_export' && enterpriseInfo.enterpriseType !== '1' && enterpriseInfo.enterpriseType !== '2'" label="供应商名称" prop="entityName" :show-overflow-tooltip="true" />
            <el-table-column label="HS编码" prop="hsCode" :show-overflow-tooltip="true" />
            <el-table-column label="商品名称" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="报关品名" prop="declarationName" :show-overflow-tooltip="true" />
            <el-table-column label="型号" prop="model" :show-overflow-tooltip="true" />
            <el-table-column label="申报计量单位" prop="measurementUnit" :show-overflow-tooltip="true" />
            <el-table-column label="包装规格" prop="packSpec" :show-overflow-tooltip="true" />
            <el-table-column prop="priceUnit" label="销售单价 (USD)" :show-overflow-tooltip="true">
              <template #default="scope">
                <span>{{ formatMoney(scope.row.priceUnit) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="增值税退税率（%）" prop="addedTaxRate" :show-overflow-tooltip="true">
              <template #default="scope">
                <span>{{ Number(scope.row.addedTaxRate)*100 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="number" label="数量">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.number"
                  type="number"
                  placeholder="请输入"
                  @change="numberChange(row)"
                />
              </template>
            </el-table-column>
            <!-- <el-table-column prop="amount" label="商品金额 (USD)" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ formatMoney(scope.row.amount) }}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" width="60">
              <template slot-scope="scope">
                <div style="color: #FE7D0B; cursor: pointer;">
                  <span @click="deleteGoods( scope.$index)">删除</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <cy-info-title>订单信息</cy-info-title>
        <el-form-item label="订单金额(USD)" prop="amount">
          <cy-amount-input v-model="ruleForm.amount" disabled />
        </el-form-item>
      </div>
    </el-form>

    <div class="submit-btn">
      <el-button @click="() => { $router.push({name: 'SalesBill'}) }">返回</el-button>
      <el-button type="primary" @click="submitClick('save')">暂存</el-button>
      <el-button v-if="step === 1" type="primary" @click="prevStep()">上一步</el-button>
      <el-button v-if="step === 0" type="primary" @click="nextStep()">下一步</el-button>
      <el-button v-if="step === 1" type="primary" @click="submitClick('submit')">提交</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import store from '@/store'
import { handleMoney } from '@/utils'
import { getMyEnterprise } from '@/api/myTrade/salesContract'
import { getImport, getSalesContract, getSalesOrderGoods, saveOrder, submitOrder, getSalesOrderDetail } from '@/api/myTrade/salesBill'
export default {
  components: {
  },
  props: {
    source: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      ruleForm: {
        id: null,
        // orderNo: '',
        importerId: '',
        saleContractId: '',
        agencyName: '',
        salesContractNo: '',
        amount: null
      },
      rules: {
        importerId: [
          { required: true, message: `请选择进口商`, trigger: 'change' }
        ],
        saleContractId: [
          { required: true, message: '请选择销售合同', trigger: 'blur' }
        ]

      },
      columns: [
        {
          type: 'selection'
        },
        {
          label: '序号',
          index: true
        },
        {
          label: '供应商名称',
          showTooltip: true,
          prop: 'entityName'
        },
        {
          label: 'HS编码',
          showTooltip: true,
          prop: 'hsCode'
        },
        {
          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',
        //   render: (h, row) => {
        //     return <div> <el-tooltip class='item' effect='dark' content={String(row.number)} placement='top'>
        //       <div class='one-ellipsis'>
        //         {String(row.number)}
        //       </div>
        //     </el-tooltip></div>
        //   }
        // },
        {
          label: '销售单价 (USD)',
          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: '商品金额 (USD)',
        //   showTooltip: true,
        //   prop: 'amount',
        //   render: (h, row) => {
        //     return <div> <el-tooltip class='item' effect='dark' content={handleMoney(row.amount)} placement='top'>
        //       <div class='one-ellipsis'>
        //         {handleMoney(row.amount)}
        //       </div>
        //     </el-tooltip></div>
        //   }
        // }
      ],
      disabled: false,
      editContractDisabled: false,
      editImporterDisabled: false,
      importerEnterpriseName: '',
      importerCertNo: '',
      exportType: '',
      searchGoodsName: '',
      goodsInfoList: [],
      selectedGoods: [],

      step: 0,
      salesContractOriginList: [],
      salesContractList: [],
      importerList: []
    }
  },
  computed: {
    ...mapGetters([
      'constant', 'enterpriseInfo'
    ]),
    formatMoney() {
      return (val) => {
        return handleMoney(val)
      }
    }
  },
  watch: {
    selectedGoods: {
      handler(newV) {
        let price = 0
        this.selectedGoods.forEach(item => {
          price += Number(item.amount)
        })

        this.ruleForm.amount = price ? price.toFixed(2) : 0
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.ruleForm.customerUserId = store.getters.userInfo.id
    this.$store.dispatch('getConstant', ['sys_yes_no', 'enterprise_type', 'district_code', 'export_type', 'tax_authority_area'])

    // 代理出口 || 内资生产企业 外商投资生产企业 --无供应商列
    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 !== '供应商名称')
    }

    if (this.source === 'edit') {
      Promise.all([
        this.queryMyEnterprice(),
        this.getImporterList(),
        this.getSalesList()
      ]).then(results => {
        this.getDetails()
      })
        .catch(error => { console.log(error) })
    } else {
      this.queryMyEnterprice()
      this.getImporterList()
      this.getSalesList()
    }
  },
  methods: {

    async submitClick(type) {
      await this.validate(type)
      const goodsList = []
      this.selectedGoods.map(item => {
        goodsList.push({
          // id: item.id,
          salesCommodityId: item.id,
          saleOrderId: this.ruleForm.id,
          hsCode: item.hsCode,
          name: item.name,
          unit: item.measurementUnit,
          packingSpecifications: item.packSpec,
          model: item.model,
          declarationName: item.declarationName,
          price: item.priceUnit,
          priceTotal: item.amount,
          taxRefundRate: item.addedTaxRate,
          count: item.number,
          vendorEntityNo: item.entityNo
        })
      })
      const data = {
        Loading: true,
        salesOrder: {
          id: this.ruleForm.id,
          customerUserId: this.ruleForm.customerUserId,
          // orderNo: this.ruleForm.orderNo,
          importerId: this.ruleForm.importerId,
          saleContractId: this.ruleForm.saleContractId,
          amount: this.ruleForm.amount ? Number(this.ruleForm.amount) : null

        },
        salesOrderGoodsList: goodsList.length ? goodsList : null
      }
      if (type === 'save') {
        saveOrder(data).then(res => {
          this.$message.success('保存成功')
          this.$router.go(-1)
        })
      } else {
        submitOrder(data).then(res => {
          this.$message.success('提交成功')
          this.$router.go(-1)
        })
      }
    },

    async validate(type) {
      var params = {
        ...this.ruleForm
      }
      return new Promise((resolve, reject) => {
        if (type === 'submit') {
          this.$refs.ruleFormRef.validate(valid => {
            if (valid) {
              const multipleList = this.$refs.commTable.multipleSelection
              if (!multipleList.length) {
                this.$message.warning('请选择商品')
                return
              }
              if (this.step === 0) {
                this.step = 1
                return resolve(params)
              } else {
                return resolve(params)
              }
            } else {
              reject()
              return false
            }
          })
        } else {
          resolve(params)
        }
      })
    },

    async getDetails() {
      const { id } = this.$route.query
      getSalesOrderDetail({ id: id, is4Update: true }).then(res => {
        const { data } = res
        this.ruleForm = data.salesOrderVO
        this.importerCertNo = data.salesOrderVO.importerId
        this.getGoodsList().then(resp => {
          if (data.salesOrderGoodsList) {
            const selectedGoods = []
            data.salesOrderGoodsList.map(item => {
              this.goodsInfoList.map(goods => {
                if (goods.id === item.salesCommodityId) {
                  selectedGoods.push(goods)
                }
              })
            })
            this.$refs.commTable.toggleRowSelection(selectedGoods)
          }
        })

        if (this.ruleForm.importerId) {
          this.editImporterDisabled = true
        }
        if (this.ruleForm.saleContractId) {
          this.editContractDisabled = true
        }
      })
    },

    // 上一步
    prevStep() {
      this.step = 0
      this.$refs.commTable.toggleRowSelection(this.selectedGoods)
    },

    // 下一步
    async nextStep() {
      if (this.source === 'view') {
        this.step = 1
      } else {
        await this.validate('submit')
        const multipleList = this.$refs.commTable.multipleSelection
        this.selectedGoods = multipleList
      }
    },

    importerChange(val) {
      this.importerCertNo = ''
      if (val) {
        this.importerCertNo = this.importerList.filter(item => {
          return item.id === val
        })[0].certNo

        this.importerEnterpriseName = this.importerList.filter(item => {
          return item.id === val
        })[0].entityName
        console.log(this.importerEnterpriseName)

        this.salesContractList = this.salesContractOriginList.filter(ele => {
          console.log(this.importerEnterpriseName, ele.importerEnterpriseName)
          return ele.importerEnterpriseName === this.importerEnterpriseName
        })
      }
      this.getGoodsList()
    },
    salesChange(val) {
      this.searchGoodsName = ''
      if (val) {
        this.ruleForm.salesContractNo = this.salesContractList.filter(item => {
          return item.id === val
        })[0].contractNo
        this.ruleForm.agencyName = this.salesContractList.filter(item => {
          return item.id === val
        })[0].agencyEnterpriseName
        this.getGoodsList()
      } else {
        this.goodsInfoList = []
        this.ruleForm.salesContractNo = ''
        this.ruleForm.agencyName = ''
      }
    },

    async getGoodsList() {
      const params = {
        page: 1,
        rows: 999,
        importerCertNo: this.importerCertNo,
        salesContractId: this.ruleForm.saleContractId,
        name: this.searchGoodsName
      }
      return new Promise((resolve, reject) => {
        getSalesOrderGoods(params).then(res => {
          this.goodsInfoList = res.data.list || []
          return resolve()
        })
      })
    },
    deleteGoods(index) {
      this.selectedGoods.splice(index, 1)
      if (this.selectedGoods.length === 0) {
        this.step = 0
        this.$refs.commTable.toggleRowSelection([])
        // this.$refs.commTable.multipleSelection = []
      }
    },
    numberChange(row) {
      if (row.number !== '' || row.number !== null) {
        row.amount = row.number * row.priceUnit
      }
    },

    getImporterList() {
      const userId = store.getters.userInfo.id
      getImport({ userId: userId }).then(res => {
        this.importerList = res.data || []
      })
    },
    getSalesList() {
      getSalesContract().then(res => {
        this.salesContractOriginList = res.data || []
        this.salesContractList = res.data || []
      })
    },
    // 查询企业
    async queryMyEnterprice() {
      const res = await getMyEnterprise()
      if (res.success) {
        this.exportType = res.data.exportType
      }
    }
  }
}
</script>

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