<template>
  <div class="form-page">
    <div class="page-head">
      <div class="page-title">{{ form.id ? '编辑销售订单' : '新增销售订单' }}</div>
      <div class="head-btn">
        <el-button size="mini" @click="onGoBack">返回</el-button>
        <el-button type="primary" size="mini" :loading="loading" @click="onEdit">提交</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="订单编号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单编号" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售类型" prop="typeNo">
              <el-select v-model="form.typeNo" class="form-item" clearable placeholder="请选择 订单销售类型">
                <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="销售组织" prop="orgNo">
              <el-select v-model="form.orgNo" class="form-item" clearable placeholder="请选择 销售组织">
                <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="分销渠道" prop="channelNo">
              <el-select v-model="form.channelNo" class="form-item" clearable placeholder="请选择 分销渠道">
                <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="订单原因" prop="reasonNo">
              <el-select v-model="form.reasonNo" class="form-item" clearable placeholder="请选择 订单原因">
                <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="销售办事处" prop="agencyNo">
              <el-select v-model="form.agencyNo" class="form-item" clearable placeholder="请选择 销售办事处">
                <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="销售小组" prop="groupNo">
              <el-select v-model="form.groupNo" class="form-item" clearable placeholder="请选择 销售小组">
                <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="客户名称" prop="clientNo">
              <el-input v-model="form.clientName" readonly placeholder="请选择客户">
                <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="客户采购单号" prop="purchaseNo">
              <el-input v-model="form.purchaseNo" placeholder="请输入 客户采购单号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售币别" prop="currencyNo">
              <el-select v-model="form.currencyNo" class="form-item" clearable placeholder="请选择 销售币别">
                <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="要求交货期" prop="deliveryDate">
              <el-date-picker v-model="form.deliveryDate" class="form-item" type="date" placeholder="选择交货日期" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="贸易条款" prop="clauseNo">
              <el-select v-model="form.clauseNo" class="form-item" clearable placeholder="请选择 国际贸易条款">
                <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="条款地址" prop="clauseAddr">
              <el-input v-model="form.clauseAddr" placeholder="请输入国际贸易条款地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="付款条件" prop="clauseAddr">
              <el-select v-model="form.paymentClause" class="form-item" clearable placeholder="请选择 付款条件代码">
                <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="凭证货币中销售订单的">
            <el-form-item label="净值" prop="netValue">
              <el-input v-model="form.netValue" placeholder="请输入凭证货币中销售订单的净值"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货方式" prop="despatchType">
              <el-select v-model="form.despatchType" class="form-item" placeholder="请选择发货方式">
                <el-option label="款到发货" value="1"/>
                <el-option label="款到生产" value="2"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="条码" prop="barCode">
              <el-input v-model="form.barCode" placeholder="请输入条码"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="加急" prop="urgent">
              <el-select v-model="form.urgent" class="form-item" placeholder="请选择加急">
                <el-option label="加急" value="1"/>
                <el-option label="不加急" value="0"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="osp订单号" prop="ospNo">
              <el-input v-model="form.ospNo" placeholder="请输入osp订单号"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="总金额" required>
              <el-input type="number" v-model="totalAmount" placeholder="请输入 总金额" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="跟单人" prop="merchandiser" clearable filterable remote :remote-method="getUserList">
              <el-select v-model="form.merchandiser" class="form-item" placeholder="请选择 跟单人" 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="采购订单日期" prop="purchaseDate">
              <el-date-picker v-model="form.purchaseDate" class="form-item" type="date" placeholder="请选择客户采购订单日期" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户定制信息" prop="custom">
              <el-input v-model="form.custom" placeholder="请输入客户定制信息"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单状态" prop="state">
              <el-select v-model="form.state" class="form-item" clearable placeholder="请选择订单状态">
                <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="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入 备注" 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="详情" 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']"
              >新增
              </el-button>
            </el-col>
          </el-row>
          <div class="page-item">
            <el-table :data="form.detailList" max-height="600">
              <el-table-column label="产品编码" prop="itemNo" show-overflow-tooltip/>
              <el-table-column label="产品名称" prop="itemName" show-overflow-tooltip/>
              <el-table-column label="总数量" prop="totalNum" show-overflow-tooltip/>
              <el-table-column label="loss%" prop="lossNum"/>
              <el-table-column label="数量" prop="num" show-overflow-tooltip/>
              <el-table-column label="单价" :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="客户指令号" 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="订单量" 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="备注" prop="remark" show-overflow-tooltip/>-->
              <el-table-column label="状态" 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="操作" width="85">
                <template slot-scope="{row, $index}">
                  <el-button v-hasPermi="['od:salesOrder:edit']" size="mini" type="text" @click="onShowEditDetail(row, $index)">编辑</el-button>
                  <el-button v-hasPermi="['od:salesOrder:edit']" size="mini" type="text" @click="onShowItemDetail(row, $index)">尺码</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

    </div>

    <el-dialog :visible.sync="showEditDetail" title="订单详情" 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="产品编码" prop="">
              <el-input v-model="itemForm.itemNo" readonly placeholder="请选择产品">
                <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="产品名称">
              <el-input v-model="itemForm.itemName" placeholder="" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="总数量">
              <el-input v-model="itemForm.totalNum" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="loss%">
              <el-input v-model="itemForm.lossNum" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="数量">
              <el-input v-model="itemForm.num" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="单价">
              <el-input v-model="itemForm.price" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="装运点">
              <el-select v-model="itemForm.shipmentPointNo" class="form-item" clearable placeholder="请选择 装运点">
                <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="存储地点">
              <el-input v-model="itemForm.storeAddr" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="批次号">
              <el-input v-model="itemForm.batchNo" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="实际交货日期">
              <el-date-picker clearable v-model="itemForm.actualDeliveryDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择实际交货日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="定价值">
              <el-input v-model="itemForm.pricingVal" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="报价单位">
              <el-input v-model="itemForm.offerUnit" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="销售单位">
              <el-input v-model="itemForm.saleUnit" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="尺码单位">
              <el-input v-model="itemForm.sizeUnit" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="客户订单号">
              <el-input v-model="itemForm.poOrderNo" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="客户产品代码">
              <el-input v-model="itemForm.clientItemNo" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="客户产品名称">
              <el-input v-model="itemForm.clientItemName" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="客户尺码单位">
              <el-input v-model="itemForm.clientSizeUnit" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="客户指令号">
              <el-input v-model="itemForm.clientCmd" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="客户单重">
              <el-input v-model="itemForm.clientKg" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="销线">
              <el-input v-model="itemForm.salePath" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="段别">
              <el-input v-model="itemForm.segment" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="版面">
              <el-input v-model="itemForm.layout" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="季度">
              <el-input v-model="itemForm.quarter" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="整/半码">
              <el-input v-model="itemForm.wholeSize" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="特殊尺码">
              <el-input v-model="itemForm.specSize" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="po号">
              <el-input v-model="itemForm.poNo" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="wip号">
              <el-input v-model="itemForm.wipNo" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="装箱数">
              <el-input v-model="itemForm.packingNum" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="周期">
              <el-input v-model="itemForm.cycle" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="sk号">
              <el-input v-model="itemForm.skNo" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="专利号">
              <el-input v-model="itemForm.patentNo" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="材质描述">
              <el-input v-model="itemForm.materialDesc" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="签收人">
              <el-input v-model="itemForm.signer" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="ShipToId">
              <el-input v-model="itemForm.shipToId" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="交货日期">
              <el-date-picker clearable v-model="itemForm.deliveryDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择交货日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="尺码组">
              <el-input v-model="itemForm.sizeGroup" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="订单量">
              <el-input v-model="itemForm.orderNum" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="条码">
              <el-input v-model="itemForm.barCode" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="印刷方向">
              <el-input v-model="itemForm.printingDirection" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="产品规格">
              <el-input v-model="itemForm.prodSpec" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="客户工厂代号">
              <el-input v-model="itemForm.plantCode" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="包装方式">
              <el-input v-model="itemForm.packMode" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="备注">
              <el-input v-model="itemForm.remark" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="" label="状态">
              <el-select v-model="itemForm.state" class="form-item" clearable placeholder="请选择状态">
                <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">取消</el-button>
        <el-button type="primary" @click="onEditDetail">确认</el-button>
      </div>
    </el-dialog>

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

    <el-dialog :visible.sync="showSpecDetail" title="产品特性详情" 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">取消</el-button>
        <el-button type="primary" @click="onEditSpec">确认</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: '请输入订单编号', trigger: ['change'] },
        clientId: { required: true, message: '请选择客户', trigger: ['change'] },
        deliveryDate: { required: true, message: '请选择交货日期', trigger: ['change'] },
        amount: { required: true, message: '请输入订单总金额', trigger: ['blur'] },
        merchandiser: { required: true, message: '请选择更进入', trigger: ['change'] },
        state: { required: true, message: '请选择订单状态', trigger: ['change'] }
      },
      itemRules: {
        itemName: { required: true, message: '请选择产品名称', trigger: ['change'] },
        itemCode: { required: true, message: '请选择产品编码', trigger: ['change'] },
        num: { required: true, message: '请输入产品数量', trigger: ['blur'] },
        amount: { required: true, message: '请输入产品金额', trigger: ['blur'] },
        state: { required: true, message: '请选择产品状态', 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.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 '第' + i + '项缺少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("暂无数据")
      }
    },
    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>
