<template>
  <el-row :gutter="10">
    <el-col :span="setcol">
      <div class="flex-align-center">
        <slot name="operation"></slot>
<!--        <el-button style="margin:0 0 10px 10px" size="small" type="primary" :disabled="data.status !== '新建'" v-if="type !== 'confirmdate'" @click="drawer = true">{{setcol === 24?'添 加':'取 消'}}</el-button>-->
        <addProduct style="margin:0 0 10px 10px" v-if="type !== 'confirmdate' && data.status === '新建' " :drawer="drawer" :data="data"  ref="addProduct"
                    :params="paramsAdd" :tablecolsAdd="tablecolsAdd" title="添 加" :tradefield="data.tradefield"
                    @addSuccess="addProducts" @addProduct="addProduct" @uploadData="uploadData" @closeDrawer="listData"
        ></addProduct>
        <excel style="margin:0 0 10px 10px" :tablecols="columnTitle" :param="param" :total="total" :excelTitle="excelTitle"></excel>
         <uploadAllData
         v-if="type !== 'confirmdate' && data.status === '新建' "
          style="margin:0 0 10px 10px"
          :total="total" 
          @onSuccess="listData()"
          @handlePullApi="handlePullApi"
          @handleDelApi="handleDelApi"
          idName="sa_orderitemsid"
          type="del"
        ></uploadAllData>
      </div>
      <p class="normal-margin" style="font-size: 13px !important;color:red;font-weight: normal" v-if="data.status === '新建'">{{checkFreefreightamount}}</p>
      <el-table
        ref="multipleTable"
        :data="tableData"
        size="small"
        max-height="500px"
        stripe
        border
        @selection-change	="selectionChange">
        <el-table-column
          type="selection"
          width="55"
          fixed="left"
          align="center">
        </el-table-column>
        <el-table-column
            prop="rowno"
            label="行号"
            width="50"
            fixed="left">
        </el-table-column>
        <el-table-column
          prop="itemname"
          label="产品名称"
          width="180"
          fixed="left">
        </el-table-column>
        <el-table-column
          prop="itemno"
          label="产品编号"
          width="180"
          fixed="left">
        </el-table-column>
        <el-table-column
          prop="erpitemno"
          label="erp编号"
          width="180">
        </el-table-column>
        <el-table-column
            prop="model"
          label="型号"
          width="150">
          <template slot-scope="scope">
            <p><span>{{scope.row.model}}</span></p>
          </template>
        </el-table-column>
        <el-table-column
            prop="spec"
            label="规格"
            width="150">
          <template slot-scope="scope">
            <p><span>{{scope.row.spec}}</span></p>
          </template>
        </el-table-column>
        <el-table-column
          prop="qty"
          label="数量"
          width="180">
          <template slot-scope="scope">
            <el-input-number :controls="true" controls-position='right' :step-strictly="true" v-if="data.status === '新建' && data.type !=='特殊订单'" size="mini" v-model="scope.row.qty" :min="scope.row.orderminqty" :step="scope.row.orderaddqty" label="输入数量" @change="rowChange(scope.row,scope.$index)"></el-input-number>
            <el-input-number :controls="true" controls-position='right' :step-strictly="true" v-else-if="data.status === '新建' && data.type ==='特殊订单'" size="mini" v-model="scope.row.qty" label="输入数量" @change="rowChange(scope.row,scope.$index)"></el-input-number>
            <span v-else>{{scope.row.qty}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="needdate"
          label="需求日期"
          width="180">
          <template slot="header" slot-scope="scope">
            <div>
              <el-date-picker
                style="width:150px"
                v-if="data.status === '新建'"
                v-model="value2"
                value-format="yyyy-MM-dd"
                slot="reference"
                align="right"
                type="date"
                size="mini"
                placeholder="一键填写需求日期"
                @change="dateChangeNeed">
              </el-date-picker>
              <span v-else>需求日期</span>
            </div>
          </template>
          <template slot-scope="scope">
            <el-date-picker
              v-if="scope.row.delivery > 0 && data.status === '新建'"
              v-model="scope.row.needdate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              size="mini"
              style="width:150px"
              :picker-options="pickerOptions1"
              @change="rowChange(scope.row)">
            </el-date-picker>
            <div v-else>
              <p v-if="scope.row.delivery === 0 ">不管控交期</p>
              <p v-else>{{scope.row.needdate}}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="deliverydate"
            label="回复交期"
            width="200">
          <template slot="header" slot-scope="scope">
            <div>
              <el-date-picker
                style="width:180px"
                v-if="type === 'confirmdate'"
                v-model="value2"
                value-format="yyyy-MM-dd"
                slot="reference"
                align="right"
                type="date"
                size="mini"
                placeholder="一键回复交期"
                @change="dateChange">
              </el-date-picker>
              <span v-else>回复交期</span>
            </div>
          </template>
          <template slot-scope="scope">
            <el-date-picker
              v-if="scope.row.delivery > 0 && type === 'confirmdate'"
              v-model="scope.row.deliverydate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              size="mini"
              style="width:150px"
              :picker-options="pickerOptions"
              @change="onDateChange(scope.row)"
              @focus="setPickerOptions(scope.row)">
            </el-date-picker>
            <div v-else>
              <p v-if="scope.row.delivery === 0 ">不管控交期</p>
              <p v-else>{{scope.row.deliverydate}}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="unit"
          label="计量单位"
          width="90">
          <template slot-scope="scope">
            <el-tag size="mini" type="info" effect="plain">{{scope.row.unit}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="marketprice"
          label="牌价"
          width="100">
          <template slot-scope="scope">
            <p>¥&nbsp;{{tool.formatAmount(scope.row.marketprice,2)}}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="defaultprice"
          label="折前价格"
          width="100">
          <template slot-scope="scope">
            <el-input v-if="data.status === '新建' && data.type === '特殊订单'" v-model="scope.row.defaultprice"  placeholder="输入订单备注" size="mini" @change="rowChange(scope.row,scope.$index)"></el-input>
            <p v-else>¥&nbsp;{{tool.formatAmount(scope.row.defaultprice,2)}}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="defaultamount"
          label="折前金额"
          width="100">
          <template slot-scope="scope">
            <p>¥&nbsp;{{tool.formatAmount(scope.row.defaultamount,2)}}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="折后价格"
          width="100">
          <template slot-scope="scope">
            <p>¥&nbsp;{{tool.formatAmount(scope.row.price,2)}}</p>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="折后价格"
          prop="totalprice">
          <template slot-scope="scope">
            <p style="color:red;font-weight:500">¥&nbsp;{{scope.row.price}}</p>
          </template>
        </el-table-column> -->
        <el-table-column
          label="折后金额"
          prop="amount">
          <template slot-scope="scope">
            <p style="color:red;font-weight:500">¥&nbsp;{{tool.formatAmount(scope.row.amount,2)}}</p>
          </template>
        </el-table-column>
        <el-table-column
            prop="cansaleqty"
            label="库存数量"
            width="100">
        </el-table-column>
        <el-table-column
            prop="stockstatus"
            label="库存状态"
            width="100">
        </el-table-column>
        <el-table-column
          prop="undeliqty"
          label="未发货数量"
          width="100">
        </el-table-column>
        <el-table-column
          prop="invoiceamount"
          label="已开票金额"
          width="100">
        </el-table-column>
        <el-table-column
          prop="writeoffamount"
          label="已核销金额"
          width="100">
        </el-table-column>
        <el-table-column
          v-if="checkNB"
          prop="stockname"
          label="仓库"
          width="150">
          <template slot-scope="scope">
            <el-select v-model="scope.row.stockno" size="mini" @visible-change="queryStock(scope.row)" placeholder="请选择">
              <el-option
                v-for="item in stockOptions"
                :key="item.WAREHOUSE"
                :label="item.WAREHOUSE"
                :value="item.WAREHOUSE"
                @click.native="stockChange(item,scope.row,scope.$index)">
                <span>{{ item.WAREHOUSE }}</span>
                <div style="float: right; color: #8492a6; font-size: 13px">数量:{{item.qty}}仓位:{{ item.LOCATION }}/批号:{{ item.LOT }}</div>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkNB"
          prop="position"
          label="仓位"
          width="150">
          <template slot-scope="scope">
            <el-input size="mini" readonly v-model="scope.row.position" @input="rowChange(scope.row,scope.$index)" placeholder="输入仓位"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkNB"
          prop="batchno"
          label="批号"
          width="150">
          <template slot-scope="scope">
            <el-input size="mini" readonly v-model="scope.row.batchno" @input="rowChange(scope.row,scope.$index)" placeholder="输入批号"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="material"
          label="材质"
          width="100">
        </el-table-column>
        <el-table-column
          prop="prodline"
          label="产线"
          width="100">
        </el-table-column>
        <el-table-column
          prop="device"
          label="装置"
          width="100">
        </el-table-column>
        <el-table-column
          prop="specalnote"
          label="特殊说明"
          width="100">
        </el-table-column>
        <el-table-column
          label="备注"
          width="300"
          prop="remarks">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remarks" placeholder="输入订单备注" size="mini" @change="rowChange(scope.row,scope.$index)"></el-input>
            <!-- <p v-else>{{scope.row.remarks}}</p> -->
          </template>
        </el-table-column>
        <el-table-column v-if="data.status === '新建'" width="90" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="deleteOrderProduct(scope.row)">删 除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:16px;text-align:right">
        <el-pagination
          background
          small
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="param.content.pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-col>
    <el-col :span="24 - setcol">
      <el-drawer
        title="添加商品"
        :visible.sync="drawer"
        append-to-body
        size="80%"
        direction="rtl">
          <div class="drawer__panel">
            <addProduct :drawer="drawer" :data="data" @onConfirm="onConfirm" ref="addpro"
                        :params="paramsAdd"
            ></addProduct>
          </div>
      </el-drawer>
    </el-col>
    <el-dialog
      title=""
      :visible.sync="progressVisible"
      :show-close="false"
      append-to-body
      width="500px">
      <el-progress v-if="totalPage" :percentage="Math.floor(progress / totalPage * 100)"></el-progress>
    </el-dialog>
  </el-row>
</template>

<script>
/*import addProduct from './addProduct.vue'*/
import addProduct from '@/template/addProduct/index'
import excel from '../export_excel.vue'
import uploadAllData from '@/components/uploadAllData/index'
export default {
  props:['data','type'],
  components:{
    excel,
    addProduct,
    uploadAllData
  },
  computed: {
    checkNB () {
      let siteid = JSON.parse(sessionStorage.getItem('active_account')).siteid
      if (siteid === 'NB' && this.data.type === '特殊订单' && this.data.typemx === '样品') {
        return true
      } else {
        return false
      }
    },
    checkFreefreightamount () {
      let result = ''
      switch (this.freefreightamount) {
        case -1:
          result = '不免运费'
          break;
        case 0:
          result = '免运费'
          break;
        default:
          result = this.data.amount >= this.freefreightamount?'当前订单免运费':`订单满${this.tool.formatAmount(this.freefreightamount,2)}元免运费,当前还差${this.tool.formatAmount(this.freefreightamount - this.data.amount,2)}元`
          break;
      }
      return result
    }
  },
  data () {
    return {
      freefreightamount:null,
      drawer:false,
      dataRefresh:true,
      setcol:24,
      tableData:[],
      tablecols:[],
      columnTitle:[],
      excelTitle:'订单明细',
      param:{
        "id": 20221109093902,
        "content": {
          "sa_orderid": this.$route.query.id, //订单ID
          "pageNumber": 1,
          "pageSize": 10000,
          "where": {
            "condition": ""
          }
        },
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < new Date().getTime();
        },
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < (new Date().getTime() - 24 * 60 * 60 * 1000);
        },
      },
      total:0,
      currentPage:0,
      time: null,
      value2:'',
      stockOptions:[],
      totalPage:0,
      progress:0,
      progressVisible:false,
      deleteIds:[],
      paramsAdd:{
        "id": null,
        "content": {
          "sa_orderid": this.$route.query.id, //订单ID
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": ""
          }
        },
      },
      tablecolsAdd:[]
    }
  },
  methods:{
    async listData () {
      this.param.content.sa_orderid = this.$route.query.id
      const res = await this.$api.requested(this.param)
      this.tableData = res.data
      this.total = res.total
      this.totalPage = Math.ceil(this.total /200)
      this.currentPage = res.pageNumber
      this.queryBasicInfo()
    },
    handlePullApi (pullApi) {
      pullApi.content = {
        "sa_orderid": 0, //订单ID
        "pageNumber": 1,
        "pageSize": 20,
        "where": {
          "condition": ""
        }
      }
      pullApi.id = 20221109093902
      pullApi.content.sa_orderid = this.$route.query.id
    },
    handleDelApi (delApi,data) {
      delApi.id = 20221109093702
      delApi.content = {
        "sa_orderid":this.$route.query.id,
        "sa_orderitemsids": data
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.content.pageSize = val
      this.listData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.param.content.pageNumber = val
      this.listData()
    },
    async deleteOrderProduct (row) {
      const res = await this.$api.requested({
        "id": 20221109093702,
        "content": {
          "sa_orderid":this.$route.query.id,
          "sa_orderitemsids": Object.prototype.toString.call(row).indexOf('Array') != -1 ? row : [row.sa_orderitemsid]
        },
      })
      this.tool.showMessage(res,()=>{
        this.listData()
        this.$emit('onSuccess')
        this.deleteIds = []
      })
    },
    stockChange (item,row,index) {
      row.stockno = item.WAREHOUSE
      row.position = item.LOCATION
      row.batchno = item.LOT
      this.$set(this.tableData,index,row)
      this.updateOrder({
        "sa_orderid": this.data.sa_orderid, //订单ID
        "sys_enterpriseid": this.data.sys_enterpriseid, //企业ID
        "sa_contractid": this.data.contacts.contactsid, //合同ID
        "type": this.data.type, //订单类型
        "items": this.tableData
      })
    },
    rowChange (val,index) {
      let that = this
      if(this.time !== null){
        clearTimeout(this.time);
      }
      this.time = setTimeout(() => {
        this.$set(this.tableData,index,val)
        that.updateOrder({
          "sa_orderid": this.data.sa_orderid, //订单ID
          "sys_enterpriseid": this.data.sys_enterpriseid, //企业ID
          "sa_contractid": this.data.contacts.contactsid, //合同ID
          "type": this.data.type, //订单类型
          "items": this.tableData
        })
      },500)
    },
    onDateChange (val){
      let that = this
      that.updateOrder({
        "sa_orderid": this.data.sa_orderid, //订单ID
        "sys_enterpriseid": this.data.sys_enterpriseid, //企业ID
        "sa_contractid": this.data.contacts.contactsid, //合同ID
        "type": this.data.type, //订单类型
        "items": this.tableData
      })
    },
    async updateOrder (val,fn) {
      const res  = await this.$api.requested({
        "id": 20221109093602,
        "content": val
      })
       if (res.code == 1) {
        this.$emit('onSuccess')
        this.listData()
      } else {
        this.$message({
          message:res.data + ':' + res.msg,
          type:'error'
        })
      }
     
    },
    async dateChangeNeed(val){
      const res = await this.$api.requested({
        "id": 20230104143802,
        "content": {
          "sa_orderid": this.data.sa_orderid, 
          "needdate": this.value2
        },
      })
      this.listData()
    },
    setPickerOptions (val) {
      // /* 如果设置需求日 交期不能大于需求日 */
      // if (val.needdate) {
      //   var startDate = val.needdate
      //   startDate = startDate.replace(new RegExp("-","gm"),"/")
      //   var startDateM = (new Date(startDate)).getTime()
      //   this.pickerOptions = {
      //     disabledDate(time) {
      //       return time.getTime() > startDateM;
      //     },
      //   }
      // /* 否则不能小于今天 */
      // } else {
      //   this.pickerOptions = {
      //     disabledDate(time) {
      //       return time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000;
      //     },
      //   }
      // }
      this.pickerOptions = {
        disabledDate(time) {
          return time.getTime() < new Date().getTime();
        },
      }
    },
    async dateChange (row) {
      this.tableData = this.tableData.filter(e=>{
        if (e.delivery > 0) {
          e.deliverydate = this.value2
        }
        return e
      })
      const res = await this.$api.requested({
       "id": 20230104143102,
        "content": {
          "sa_orderid": this.$route.query.id, 
          "deliverydate": this.value2
        },
      })
    },
    selectionChange (selection) {
      this.$emit('select',selection)
    },
    // 订单添加商品
    async onConfirm (data,isupload) {
      if (isupload) {
        const res = await this.$api.requested({
          "id": 20221109093602,
          "content": {
            "sa_orderid": this.$route.query.id, //订单ID
            "sys_enterpriseid": this.data.sys_enterpriseid, //企业ID
            "type": this.data.type, //订单类型
            "items": data.map(e=>{
              return {
                sa_orderitemsid:0,
                itemid:e.itemid,
                qty:e.orderminqty,
                needdate:e.deliverydate
              }
            })
          },
        })
      }
      this.listData()
      this.$emit('onSuccess')
    },
    async queryStock (val) {
      const res = await this.$api.requested({
        "id": 20230228193201,
        "content": {
          "itemid": val.itemid,
          "qty": val.qty
        }

      })
      this.stockOptions = res.data
    },
    async queryBasicInfo () {
      const res = await this.$api.requested({
        "id":20220920084001,"content":{
          sys_enterpriseid:this.data.sys_enterpriseid
        },
      })
      this.freefreightamount = res.data.freefreightamount?res.data.freefreightamount:0
    },
    /*批量添加商品*/
    async addProducts(data){
      let items = data.map(item => {
        return {
          sa_orderitemsid:0,
          itemid:item.itemid,
          qty:item.orderminqty,
          needdate:item.deliverydate
        }
      })
      const res = await this.$api.requested({
        "id": 20221109093602,
        "content": {
          "sa_orderid": this.$route.query.id, //订单ID
          "sys_enterpriseid": this.data.sys_enterpriseid, //企业ID
          "type": this.data.type, //订单类型
          "items": items
        },
      })
      this.tool.showMessage(res,()=>{
        this.listData()
        this.$refs.addProduct.list = []
      })
    },
    /*单个添加商品*/
    async addProduct(data){
      let res = await this.$api.requested({
        "id": 20221109093602,
        "content": {
          "sa_orderid": this.$route.query.id,
          "sys_enterpriseid": this.data.sys_enterpriseid, //企业ID
          "type": this.data.type, //订单类型
          "items": [
            {
              "sa_orderitemsid": 0,
              "needdate": data.deliverydate,
              "qty": data.orderminqty,
              'itemid':data.itemid,
            }
          ]
        },
      })
      this.tool.showMessage(res,() => {
        this.listData()
        this.$refs.addProduct.list = []
      })
    },
    /*一键添加*/
    uploadData(uploadApi,data){
      uploadApi.id = 20221109093602
      uploadApi.content = {
        "sa_orderid": this.$route.query.id,
        "sys_enterpriseid": this.data.sys_enterpriseid, //企业ID
        "type": this.data.type, //订单类型
        "items": data.map(e=>{
          return {
            "sa_orderitemsid": 0,
            "needdate": e.deliverydate,
            "qty": e.orderminqty,
            'itemid':e.itemid,
          }
        })
      }
      this.listData()
      this.$refs.addProduct.list = []
    },

  },
  mounted () {
    this.listData()
    // this.queryStock()
    this.columnTitle  = []
    this.$refs.multipleTable.$children.forEach(obj => {

      let columnChild = {'columnname':obj.prop,'filter':0,'rowindex':'','sequence':'','title':obj.label,'width':obj.width}
      // 存到columnTitle数组中
      this.columnTitle.push(columnChild)

    })
    // console.log(this.columnTitle)
  },
  created() {
    this.tablecolsAdd = this.tool.tabelCol(this.$route.name).addProductTable.tablecols
  }
}

</script>
<style>
body .el-table th.gutter{
display: table-cell!important;
}
</style>