<template>
  <div class="form-page">
    <div class="page-head">
      <div class="page-title">{{ form.id ? $t('编辑销售订单') : $t('新增销售订单') }}</div>
      <div class="head-btn">
        <el-button size="mini" @click="onGoBack">{{ $t('common.back') }}</el-button>
        <el-button type="primary" size="mini" :loading="loading" @click="onEdit">{{ $t('common.submit') }}</el-button>
      </div>
    </div>
    <div class="page-body clearfix">
      <el-form :model="form" ref="form" :rules="rules" label-width="120px" size="mini">
        <el-row class="form-row" :gutter="10">
          <el-col :span="6">
            <el-form-item :label="$t('订单编号')" prop="orderNo">
              <el-input v-model="form.orderNo" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('销售类型')" prop="typeNo">
              <el-select v-model="form.typeNo" class="form-item" clearable :placeholder="$t('请选择 订单销售类型')">
                <el-option v-for="item in saleType" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('销售组织')" prop="orgNo">
              <el-select v-model="form.orgNo" class="form-item" clearable :placeholder="$t('请选择 销售组织')">
                <el-option v-for="item in saleOrg" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('分销渠道')" prop="channelNo">
              <el-select v-model="form.channelNo" class="form-item" clearable :placeholder="$t('请选择 分销渠道')">
                <el-option v-for="item in saleChannel" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('订单原因')" prop="reasonNo">
              <el-select v-model="form.reasonNo" class="form-item" clearable :placeholder="$t('请选择 订单原因')">
                <el-option v-for="item in saleReason" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('销售办事处')" prop="agencyNo">
              <el-select v-model="form.agencyNo" class="form-item" clearable :placeholder="$t('请选择 销售办事处')">
                <el-option v-for="item in saleOffice" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('销售小组')" prop="groupNo">
              <el-select v-model="form.groupNo" class="form-item" clearable :placeholder="$t('请选择 销售小组')">
                <el-option v-for="item in saleGroup" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('客户名称')" prop="clientNo">
              <el-input v-model="form.clientName" readonly>
                <el-button slot="append" icon="el-icon-search" @click="$refs['ClientSelector'].showFlag = true"/>
              </el-input>
              <ClientSelector ref="ClientSelector" @onSelected="onSelectClient"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('客户采购单号')" prop="purchaseNo">
              <el-input v-model="form.purchaseNo" :placeholder="$t('请输入 客户采购单号')"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('销售币别')" prop="currencyNo">
              <el-select v-model="form.currencyNo" class="form-item" clearable :placeholder="$t('请选择 销售币别')">
                <el-option v-for="item in saleCurrency" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('要求交货期')" prop="deliveryDate">
              <el-date-picker v-model="form.deliveryDate" class="form-item" type="date" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('贸易条款')" prop="clauseNo">
              <el-select v-model="form.clauseNo" class="form-item" clearable :placeholder="$t('请选择 国际贸易条款')">
                <el-option v-for="item in saleClause" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('条款地址')" prop="clauseAddr">
              <el-input v-model="form.clauseAddr"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('付款条件')" prop="clauseAddr">
              <el-select v-model="form.paymentClause" class="form-item" clearable :placeholder="$t('请选择 付款条件代码')">
                <el-option v-for="item in salePaymentClause" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :title="$t('凭证货币中销售订单的')">
            <el-form-item :label="$t('净值')" prop="netValue">
              <el-input v-model="form.netValue"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('发货方式')" prop="despatchType">
              <el-select v-model="form.despatchType" class="form-item">
                <el-option :label="$t('款到发货')" value="1"/>
                <el-option :label="$t('款到生产')" value="2"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('条码')" prop="barCode">
              <el-input v-model="form.barCode"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('加急')" prop="urgent">
              <el-select v-model="form.urgent" class="form-item">
                <el-option :label="$t('加急')" value="1"/>
                <el-option :label="$t('不加急')" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('osp订单号')" prop="ospNo">
              <el-input v-model="form.ospNo"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item :label="$t('总金额')" required>
              <el-input type="number" v-model="totalAmount" :placeholder="$t('请输入 总金额')" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('跟单人')" prop="merchandiser" clearable filterable remote :remote-method="getUserList">
              <el-select v-model="form.merchandiser" class="form-item" :placeholder="$t('请选择 跟单人')" filterable clearable>
                <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.nickName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('采购订单日期')" prop="purchaseDate">
              <el-date-picker v-model="form.purchaseDate" class="form-item" type="date" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('客户定制信息')" prop="custom">
              <el-input v-model="form.custom"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('订单状态')" prop="state">
              <el-select v-model="form.state" class="form-item" clearable>
                <el-option v-for="item in dict.type['sales_order_state']" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :offset="12" :span="12">
            <el-form-item :label="$t('common.remark')" prop="remark">
              <el-input type="textarea" v-model="form.remark" :placeholder="$t('请输入 备注')" show-word-limit maxlength="120" :rows="3"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="detail-body">

      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane :label="$t('详情')" name="detail">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="onShowEditDetail(null, form.detailList.length)"
                v-hasPermi="['od:salesOrder:add']"
              >{{$t('新增')}}</el-button>
            </el-col>
          </el-row>
          <div class="page-item">
            <el-table :data="form.detailList" max-height="600">
              <el-table-column :label="$t('产品编码')" prop="itemNo" show-overflow-tooltip/>
              <el-table-column :label="$t('产品名称')" prop="itemName" show-overflow-tooltip/>
              <el-table-column :label="$t('总数量')" prop="totalNum" show-overflow-tooltip/>
              <el-table-column label="loss%" prop="lossNum"/>
              <el-table-column :label="$t('数量')" prop="num" show-overflow-tooltip/>
              <el-table-column :label="$t('单价')" :formatter="r => this.formatMoney(r.price)" show-overflow-tooltip/>
<!--              <el-table-column label="装运点" prop="shipmentPointNo" show-overflow-tooltip/>
              <el-table-column label="存储地点" prop="storeAddr" show-overflow-tooltip/>
              <el-table-column label="批次号" prop="batchNo" show-overflow-tooltip/>
              <el-table-column label="实际交货日期" prop="actualDeliveryDate" show-overflow-tooltip/>
              <el-table-column label="定价值" prop="pricingVal" show-overflow-tooltip/>
              <el-table-column label="报价单位" prop="offerUnit" show-overflow-tooltip/>
              <el-table-column label="销售单位" prop="saleUnit" show-overflow-tooltip/>
              <el-table-column label="尺码单位" prop="sizeUnit" show-overflow-tooltip/>
              <el-table-column label="客户订单号" prop="poOrderNo" show-overflow-tooltip/>
              <el-table-column label="客户产品代码" prop="clientItemNo" show-overflow-tooltip/>
              <el-table-column label="客户产品名称" prop="clientItemName" show-overflow-tooltip/>
              <el-table-column label="客户尺码单位" prop="clientSizeUnit" show-overflow-tooltip/>-->
              <el-table-column :label="$t('客户指令号')" prop="clientCmd" show-overflow-tooltip/>
<!--              <el-table-column label="客户单重" prop="clientKg" show-overflow-tooltip/>
              <el-table-column label="销线" prop="salePath" show-overflow-tooltip/>
              <el-table-column label="段别" prop="segment" show-overflow-tooltip/>
              <el-table-column label="版面" prop="layout" show-overflow-tooltip/>
              <el-table-column label="季度" prop="quarter" show-overflow-tooltip/>
              <el-table-column label="整/半码" prop="wholeSize" show-overflow-tooltip/>
              <el-table-column label="特殊尺码" prop="specSize" show-overflow-tooltip/>
                <el-table-column label="po号" prop="poNo" show-overflow-tooltip/>
              <el-table-column label="wip号" prop="wipNo" show-overflow-tooltip/>
              <el-table-column label="装箱数" prop="packingNum" show-overflow-tooltip/>
              <el-table-column label="周期" prop="cycle" show-overflow-tooltip/>
              <el-table-column label="sk号" prop="skNo" show-overflow-tooltip/>
              <el-table-column label="专利号" prop="patentNo" show-overflow-tooltip/>
              <el-table-column label="材质描述" prop="materialDesc" show-overflow-tooltip/>
              <el-table-column label="签收人" prop="signer" show-overflow-tooltip/>
              <el-table-column label="ShipToId" prop="shipToId" show-overflow-tooltip/>
              <el-table-column label="交货日期" prop="deliveryDate" show-overflow-tooltip/>
              <el-table-column label="尺码组" prop="sizeGroup" show-overflow-tooltip/>-->
              <el-table-column :label="$t('订单量')" prop="orderNum" show-overflow-tooltip/>
<!--              <el-table-column label="条码" prop="barCode" show-overflow-tooltip/>
              <el-table-column label="印刷方向" prop="printingDirection" show-overflow-tooltip/>
              <el-table-column label="产品规格" prop="prodSpec" show-overflow-tooltip/>
              <el-table-column label="客户工厂代号" prop="plantCode" show-overflow-tooltip/>
              <el-table-column label="包装方式" prop="packMode" show-overflow-tooltip/>
              <el-table-column :label="$t('common.remark')" prop="remark" show-overflow-tooltip/>-->
              <el-table-column :label="$t('common.status')" prop="state">
                <template slot-scope="{row}">
                  {{ dict.type['sales_order_state'].find(item => item.value == row.state).label }}
                </template>
              </el-table-column>
              <el-table-column fixed="right" :label="$t('common.option')" width="85">
                <template slot-scope="{row, $index}">
                  <el-button v-hasPermi="['od:salesOrder:edit']" size="mini" type="text" @click="onShowEditDetail(row, $index)">{{$t('编辑')}}</el-button>
                  <el-button v-hasPermi="['od:salesOrder:edit']" size="mini" type="text" @click="onShowItemDetail(row, $index)">{{$t('尺码')}}</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

    </div>

    <el-dialog :visible.sync="showEditDetail" :title="$t('订单详情')" width="1200px">
      <el-form :model="itemForm" ref="itemForm" :rules="itemRules" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item :label="$t('产品编码')" prop="">
              <el-input v-model="itemForm.itemNo" readonly>
                <el-button slot="append" icon="el-icon-search" @click="$refs['ItemSelectRef'].showFlag = true"/>
              </el-input>
              <ItemSelect ref="ItemSelectRef" @onSelected="onItemSelect"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('产品名称')">
              <el-input v-model="itemForm.itemName" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('总数量')">
              <el-input v-model="itemForm.totalNum" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="loss%">
              <el-input v-model="itemForm.lossNum" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('数量')">
              <el-input v-model="itemForm.num" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('单价')">
              <el-input v-model="itemForm.price" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('装运点')">
              <el-select v-model="itemForm.shipmentPointNo" class="form-item" clearable :placeholder="$t('请选择 装运点')">
                <el-option v-for="item in saleShipmentPoint" :key="item.code" :value="item.code" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('存储地点')">
              <el-input v-model="itemForm.storeAddr" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('批次号')">
              <el-input v-model="itemForm.batchNo" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('实际交货日期')">
              <el-date-picker clearable v-model="itemForm.actualDeliveryDate" type="date" value-format="yyyy-MM-dd"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('定价值')">
              <el-input v-model="itemForm.pricingVal" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('报价单位')">
              <el-input v-model="itemForm.offerUnit" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('销售单位')">
              <el-input v-model="itemForm.saleUnit" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('尺码单位')">
              <el-input v-model="itemForm.sizeUnit" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('客户订单号')">
              <el-input v-model="itemForm.poOrderNo" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('客户产品代码')">
              <el-input v-model="itemForm.clientItemNo" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('客户产品名称')">
              <el-input v-model="itemForm.clientItemName" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('客户尺码单位')">
              <el-input v-model="itemForm.clientSizeUnit" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('客户指令号')">
              <el-input v-model="itemForm.clientCmd" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('客户单重')">
              <el-input v-model="itemForm.clientKg" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('销线')">
              <el-input v-model="itemForm.salePath" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('段别')">
              <el-input v-model="itemForm.segment" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('版面')">
              <el-input v-model="itemForm.layout" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('季度')">
              <el-input v-model="itemForm.quarter" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('整/半码')">
              <el-input v-model="itemForm.wholeSize" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('特殊尺码')">
              <el-input v-model="itemForm.specSize" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('po号')">
              <el-input v-model="itemForm.poNo" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('wip号')">
              <el-input v-model="itemForm.wipNo" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('装箱数')">
              <el-input v-model="itemForm.packingNum" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('周期')">
              <el-input v-model="itemForm.cycle" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('sk号')">
              <el-input v-model="itemForm.skNo" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('专利号')">
              <el-input v-model="itemForm.patentNo" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('材质描述')">
              <el-input v-model="itemForm.materialDesc" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('签收人')">
              <el-input v-model="itemForm.signer" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="ShipToId">
              <el-input v-model="itemForm.shipToId" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('交货日期')">
              <el-date-picker clearable v-model="itemForm.deliveryDate" type="date" value-format="yyyy-MM-dd"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('尺码组')">
              <el-input v-model="itemForm.sizeGroup" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('订单量')">
              <el-input v-model="itemForm.orderNum" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('条码')">
              <el-input v-model="itemForm.barCode" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('印刷方向')">
              <el-input v-model="itemForm.printingDirection" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('产品规格')">
              <el-input v-model="itemForm.prodSpec" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('客户工厂代号')">
              <el-input v-model="itemForm.plantCode" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('包装方式')">
              <el-input v-model="itemForm.packMode" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('common.remark')">
              <el-input v-model="itemForm.remark" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" :label="$t('common.status')">
              <el-select v-model="itemForm.state" class="form-item" clearable>
                <el-option v-for="item in dict.type['sales_order_state']" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="showEditDetail = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="onEditDetail">{{$t('确认')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="showItemDetail" :title="$t('产品尺码详情')" width="650px">
      <el-table :data="itemDetailForm.itemList" max-height="600">
        <el-table-column :label="$t('尺码')" prop="size">
          <template slot-scope="{row}">
            <el-input v-model="row.size" clearable/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('数量')" prop="num">
          <template slot-scope="{row}">
            <el-input v-model="row.num" clearable/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('loss数')" prop="lossNum">
          <template slot-scope="{row}">
            <el-input v-model="row.lossNum" clearable/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.remark')" prop="remark">
          <template slot-scope="{row}">
            <el-input v-model="row.remark" clearable/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.option')" prop="specJson" width="60">
          <template slot-scope="{row, $index}">
            <el-button v-hasPermi="['od:salesOrder:edit']" size="mini" type="text" @click="onShowSpecDetail(row, $index)">{{$t('特性')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="showItemDetail = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="onEditItem">{{$t('确认')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="showSpecDetail" :title="$t('产品特性详情')" width="650px">
      <el-form :model="specForm" label-width="100px">
        <el-row>
          <el-col v-for="item in specForm.specList" :key="item['specKey']" :span="12">
            <el-form-item :label="item['specKey']">
              <el-input v-model="item['specVal']"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="showSpecDetail = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="onEditSpec">{{$t('确认')}}</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>


import { addOrder, getOrder, updateOrder } from '@/api/mes/od/salesOrder'
import { getFactoryQuote } from '@/api/mes/od/factoryQuote'
import { getSalesOrder } from '@/api/mes/od/purchaseOrder'
import { listUser } from '@/api/system/user'
import { listClient } from '@/api/mes/md/client'
import ItemSelect from '@/components/itemSelect/single.vue'
import ClientSelector from '@/components/ClientSelector'
import { genCode } from '@/api/system/autocode/rule'

export default {
  components: {
    ItemSelect,
    ClientSelector,
  },
  dicts: ['sales_order_state'],
  computed: {
    totalAmount() {
      return this.form.detailList.reduce((amount = 0, item) => {
        amount += (item.price * item.totalNum)
        return amount
      }, 0) || 0
    },
  },
  data() {
    return {
      form: {
        id: null,
        purchaseNo: null,
        purchaseDate: null,
        clientId: null,
        clientNo: null,
        orderNo: null,
        typeNo: null,
        amount: null,
        merchandiser: null,
        custom: null,
        orgNo: null,
        channelNo: null,
        reasonNo: null,
        agencyNo: null,
        groupNo: null,
        currencyNo: null,
        deliveryDate: null,
        clauseNo: null,
        clauseAddr: null,
        paymentClause: null,
        netValue: null,
        despatchType: null,
        barCode: null,
        urgent: null,
        ospNo: null,
        state: null,
        detailList: []
      },
      itemForm: {
        id: null,
        orderId: null,
        itemId: null,
        itemNo: null,
        itemName: null,
        totalNum: null,
        num: null,
        lossNum: null,
        price: null,
        shipmentPointNo: null,
        storeAddr: null,
        batchNo: null,
        actualDeliveryDate: null,
        pricingVal: null,
        offerUnit: null,
        saleUnit: null,
        sizeUnit: null,
        poOrderNo: null,
        clientItemNo: null,
        clientItemName: null,
        clientSizeUnit: null,
        clientCmd: null,
        clientKg: null,
        salePath: null,
        segment: null,
        layout: null,
        quarter: null,
        wholeSize: null,
        specSize: null,
        poNo: null,
        wipNo: null,
        packingNum: null,
        cycle: null,
        skNo: null,
        patentNo: null,
        materialDesc: null,
        signer: null,
        shipToId: null,
        deliveryDate: null,
        sizeGroup: null,
        size: null,
        orderNum: null,
        barCode: null,
        printingDirection: null,
        prodSpec: null,
        plantCode: null,
        packMode: null,
        remark: null,
        state: null,
        specList: []
      },
      itemDetailForm: {
        itemList: []
      },
      specForm: {
        specList: []
      },
      rules: {
        orderNo: { required: true, message: this.$t('请输入订单编号'), trigger: ['change'] },
        clientId: { required: true, message: this.$t('请选择客户'), trigger: ['change'] },
        deliveryDate: { required: true, message: this.$t('请选择交货日期'), trigger: ['change'] },
        amount: { required: true, message: this.$t('请输入订单总金额'), trigger: ['blur'] },
        merchandiser: { required: true, message: this.$t('请选择更进入'), trigger: ['change'] },
        state: { required: true, message: this.$t('请选择订单状态'), trigger: ['change'] }
      },
      itemRules: {
        itemName: { required: true, message: this.$t('请选择产品名称'), trigger: ['change'] },
        itemCode: { required: true, message: this.$t('请选择产品编码'), trigger: ['change'] },
        num: { required: true, message: this.$t('请输入产品数量'), trigger: ['blur'] },
        amount: { required: true, message: this.$t('请输入产品金额'), trigger: ['blur'] },
        state: { required: true, message: this.$t('请选择产品状态'), trigger: ['change'] }
      },
      clientList: [],
      userList: [],
      showSpecDetail: false,
      showItemDetail: false,
      showEditDetail: false,
      activeName: 'detail',
      loading: false,

      saleChannel: [],
      saleGroup: [],
      saleOffice: [],
      saleOrg: [],
      saleType: [],
      saleUnit: [],
      saleClause: [],
      saleCurrency: [],
      salePaymentClause: [],
      saleReason: [],
      saleShipmentPoint: [],
    }
  },
  methods: {
    onEdit() {
      if (this.loading) return
      this.loading = true
      this.$refs.form.validate(valid => {
        if (valid) {
          let msg = this.checkedItem()
          if (msg) {
            this.loading = false
            return this.$message.error(msg)
          }
          this.form.amount = this.totalAmount
          let editOrder = this.form.id ? updateOrder : addOrder
          editOrder(this.form).then(() => {
            this.$message.success(this.$t('操作成功'))
            this.onGoBack()
          }).finally(() => this.loading = false)
        } else {
          this.loading = false
        }
      })
    },
    checkedItem() {
      let {detailList} = this.form
      for (let i = 0; i < detailList.length; i++) {
        let detail = detailList[i]
        if (!detail.itemId) return this.$t('第') + i + this.$t('项缺少itemId')
        // todo 检测未做
      }
      return null
    },

    onEditSpec() {
      this.showSpecDetail = false
      console.log(this.specForm)
      this.itemDetailForm.itemList[this.specForm.index]['specJson'] = JSON.stringify(this.specForm.specList)
    },
    onShowSpecDetail(row, index) {
      this.specForm.specList = JSON.parse(row['specJson']) || []
      this.specForm.index = index
      if (this.specForm.specList.length) {
        this.showSpecDetail = true
      } else {
        this.$message.error(this.$t('暂无数据'))
      }
    },
    onEditItem() {
      this.showItemDetail = false
      this.form.detailList[this.itemDetailForm.index].itemList = this.itemDetailForm.itemList
    },
    onShowItemDetail(row, index) {
      console.log(row)
      this.showItemDetail = true
      this.itemDetailForm.itemList = row.itemList
      this.itemDetailForm.index = index
    },


    onEditDetail() {
      this.showEditDetail = false
      this.$refs.itemForm.validate(valid => {
        if (valid) {
          this.form.detailList.splice(this.itemForm.index, 1, this.itemForm)
          console.log(this.form.detailList)
        }
      })
    },
    onShowEditDetail(item, $index) {
      console.log(item)
      this.showEditDetail = true
      this.$refs.itemForm && this.$refs.itemForm.resetFields()
      this.itemForm = item || { itemName: null, itemNo: null, num: null, amount: null, state: null, specList: [] }
      this.itemForm.lossPercent = (item.lossNum / item.totalNum * 100).toFixed(2)
      this.itemForm.index = $index
    },

    onSelectClient(row) {
      if (row != undefined) {
        this.form.clientId = row.clientId;
        this.form.clientCode = row.clientCode;
        this.form.clientName = row.clientName;
        this.form.sapClientCode = row.sapClientCode;
      }
    },

    onItemSelect(row) {
      if (row != undefined) {
        this.itemForm.itemId = row.itemId;
        this.itemForm.itemNo = row.itemCode;
        this.itemForm.itemName = row.itemName;
        let params = {clientId: row.clientId, itemId: row.itemId, validFrom: new Date()}
        getFactoryQuote(params).then(res => {
          this.itemForm.price = res.data.price
        })
      }
    },

    onGenCode() {
      genCode('SALES_ORDER').then(response => {
        this.form.orderNo = response
      })
    },

    onGoBack() {
      this.$store.dispatch('tagsView/delView', this.$router.currentRoute)
      this.$router.push('/order/sales')
    },

    getClientList(key) {
      listClient({ clientName: key, pageNum: 1, pageSize: 100 }).then(res => this.clientList = res.rows)
    },

    getUserList(key) {
      listUser({ nickName: key, pageNum: 1, pageSize: 100 }).then(res => this.userList = res.rows)
    },
    getDetail() {
      let { id: orderId, purchaseId } = this.$route.query
      if (orderId) {
        getOrder(orderId).then(res => {
          this.form = res.data
          this.form.detailList = this.form.detailList || []
        })
      } else if (purchaseId) {
        getSalesOrder(purchaseId).then(res => {
          this.form = res.data
          this.form.detailList = this.form.detailList || []
        })
      }
    },
    listSaleChannel() {
      this.$store.dispatch('order/getSaleChannel').then(res => {
        this.saleChannel = res
      })
    },
    listSaleGroup() {
      this.$store.dispatch('order/getSaleGroup').then(res => {
        this.saleGroup = res
      })
    },
    listSaleOffice() {
      this.$store.dispatch('order/getSaleOffice').then(res => {
        this.saleOffice = res
      })
    },
    listSaleOrg() {
      this.$store.dispatch('order/getSaleOrg').then(res => {
        this.saleOrg = res
      })
    },
    listSaleType() {
      this.$store.dispatch('order/getSaleType').then(res => {
        this.saleType = res
      })
    },
    listSaleUnit() {
      this.$store.dispatch('order/getSaleUnit').then(res => {
        this.saleUnit = res
      })
    },
    listSaleClause() {
      this.$store.dispatch('order/getSaleClause').then(res => {
        this.saleClause = res
      })
    },
    listSaleCurrency() {
      this.$store.dispatch('order/getSaleCurrency').then(res => {
        this.saleCurrency = res
      })
    },
    listSalePaymentClause() {
      this.$store.dispatch('order/getSalePaymentClause').then(res => {
        this.salePaymentClause = res
      })
    },
    listSaleReason() {
      this.$store.dispatch('order/getSaleReason').then(res => {
        this.saleReason = res
      })
    },
    listSaleShipmentPoint() {
      this.$store.dispatch('order/getSaleShipmentPoint').then(res => {
        this.saleShipmentPoint = res
      })
    },
    getSaleNos() {
      this.listSaleChannel()
      this.listSaleGroup()
      this.listSaleOffice()
      this.listSaleOrg()
      this.listSaleType()
      this.listSaleUnit()
      this.listSaleClause()
      this.listSaleCurrency()
      this.listSalePaymentClause()
      this.listSaleReason()
      this.listSaleShipmentPoint()
    }
  },
  created() {
    this.getDetail()
    this.getUserList()
    this.getClientList()
    this.getSaleNos()
  }
}
</script>

<style lang="scss" scoped>
.page-head {
  border-bottom: 1px solid #dddddd;
  box-shadow: 0 2px 2px #dddddd;
}

.page-title {
  line-height: 50px;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.head-btn {
  margin: 0 20px 20px;
}

.page-body {
  margin: 20px 40px;
}

.page-item {
  margin: 20px 40px;
}

.spec-item {
  line-height: 18px;
  font-size: 12px;
}

.spec-key {
  color: #99a9bf;
}

.detail-body {
  margin-bottom: 50px;
}

.sap-info-items-wrap {
  overflow: auto;
  width: 100%;
  max-height: 800px;
}

.items-head {
  width: max-content;
}

.items-head div {
  width: 150px;
  float: left;
  height: 40px;
  font-size: 14px;
  overflow: hidden;
  margin-right: 10px;
}

.items-body {
  width: max-content;
}

.items-body div {
  width: 150px;
  float: left;
  margin-right: 10px;
}

.form-item {
  width: 100%;
}

.form-row > div {
  min-height: 47px;
}

</style>
