<template>
<el-row :gutter="10">
  <el-col :span="setcol">
    <div  class="flex-align-center normal-margin">
      <slot name="operation"></slot>
<!--      <el-button :disabled="data.type === '特殊订单'"  v-if="data.status === '新建'" class="inline-16" size="small" type="primary" @click="drawer = true">{{setcol === 24?'添 加':'取 消'}}</el-button>-->
      <addProduct class="inline-16"  v-if="type !== 'confirmdate' && data.status === '新建' && data.type !== '特殊订单' " :drawer="drawer" :data="data"  ref="addProduct"
                  :params="paramsAdd" :tablecolsAdd="tablecolsAdd" title="添 加" :tradefield="data.tradefield"
                  @addSuccess="addProducts" @addProduct="addProduct" @uploadData="uploadData" @closeDrawer="listData"
      ></addProduct>
      <excel class="inline-16" :tablecols="columnTitle" :param="param" :total="total" :excelTitle="excelTitle"></excel>
      <uploadAllData
          v-if="type !== 'confirmdate' && data.status === '新建' && data.type !== '特殊订单' "
          :total="total"
          @onSuccess="listData()"
          @handlePullApi="handlePullApi"
          @handleDelApi="handleDelApi"
          idName="sa_orderitemsid"
          type="del"
      ></uploadAllData>
    </div>
    <p v-if="data.status === '新建'" class="normal-margin" style="font-size: 13px !important;color:red;font-weight: normal">{{checkFreefreightamount}}</p>
    <el-table
      ref="multipleTable"
      :data="tableData"
      height="500px"
      style="width: 100%;"
      max-height="410px"
      size="small"
      stripe
      border>
      <!-- <el-table-column
        type="selection"
        width="55"
        align="center">
      </el-table-column> -->
      <el-table-column
          prop="rowno"
          label="行号"
          fixed
          width="50">
      </el-table-column>
      <el-table-column
        prop="itemname"
        label="产品名称"
        fixed
        width="180">
      </el-table-column>
      <el-table-column
        prop="itemno"
        label="产品编号"
        width="180">
      </el-table-column>
      <el-table-column
        prop="erpitemno"
        label="erp编号"
        width="180">
      </el-table-column>
      <el-table-column
        label="型号"
        prop="model">
        <template slot-scope="scope">
          <p><span>{{scope.row.model}}</span></p>
        </template>
      </el-table-column>
      <el-table-column
          label="规格"
          prop="spec">
        <template slot-scope="scope">
          <p><span>{{scope.row.spec}}</span></p>
        </template>
      </el-table-column>
      <el-table-column
        label="数量"
        width="180"
        prop="qty">
        <template slot-scope="scope">
          <el-input-number 
            :controls="true" 
            controls-position='right' 
            :step-strictly="true" 
            v-if="data.status === '新建'" size="mini" 
            v-model="scope.row.qty" :min="scope.row.orderminqty" :step="scope.row.orderaddqty" label="输入数量" @change="qtyChange(scope.row,scope.$index)"></el-input-number>
          <span v-else>{{scope.row.qty}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="需求日期"
        prop="needdate"
        width="200">
        <template slot="header" slot-scope="scope">
          <div>
            <el-date-picker
              style="width:180px"
              v-if="data.status === '新建'"
              v-model="value2"
              value-format="yyyy-MM-dd"
              slot="reference"
              align="right"
              type="date"
              size="mini"
              placeholder="一键交期"
              @change="dateChange(scope.row)">
            </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="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.needdate}}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="deliverydate"
        label="回复交期"
        width="120">
      </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="price"
        label="价格"
        width="90">
        <template slot-scope="scope">
          <p style="color:red;font-weight:500">¥&nbsp;{{tool.formatAmount(scope.row.price,2)}}</p>
        </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="canUseInput" v-model="scope.row.defaultprice" @change="inputChange(scope.row,scope.$index)" placeholder="输入单价" size="mini"></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 style="color:red;font-weight:500">¥&nbsp;{{tool.formatAmount(scope.row.defaultprice * scope.row.qty,2)}}</p>
        </template>
      </el-table-column>
      <el-table-column
        label="折后价格"
        prop="price">
         <template slot-scope="scope">
            <p>¥&nbsp;{{tool.formatAmount(scope.row.price,2)}}</p>
          </template>
      </el-table-column>
      <el-table-column
        label="折后金额"
        width="150"
        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="undeliqty"
        label="未发货数量"
        width="100">
      </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="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
        prop="remarks"
        label="备注"
        width="300"
        fixed="right">
        <template slot-scope="scope">
          <el-input  type="textarea"  :disabled="data.status != '新建'" @blur="onConfirm([scope.row],true,true)" size="small" v-model="scope.row.remarks" placeholder="请输入备注"></el-input>
        </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"></addProduct>
        </div>
    </el-drawer>
  </el-col>
</el-row>
</template>

<script>
/*import addProduct from '@/template/orderCanUseProduct/index.vue'*/
import addProduct from '@/template/addProduct/index'
import uploadAllData from '@/components/uploadAllData/index'
export default {
  props:['data','type'],
  data () {
    return {
      freefreightamount:null,
      drawer:false,
      setcol:24,
      dataRefresh:true,
      tableData:[],
      columnTitle:[],
      excelTitle:'订单明细',
      param:{
        "id": 20221109093902,
        "content": {
          "sa_orderid": 0, //订单ID
          "pageNumber": 1,
          "pageSize": 20,
          "where": {
            "condition": ""
          }
        },
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < (Date.now() - 24 * 3600 * 1000);
        },
      },
      total:0,
      currentPage:0,
      time: null,
      value2:'',
      paramsAdd:{
        "id": null,
        "content": {
          "sa_orderid": this.$route.query.id, //订单ID
          "pageNumber": 1,
          "pageSize": 100,
          "where": {
            "condition": ""
          }
        },
      },
      tablecolsAdd:[]
    }
  },
  computed:{
    canUseInput () {
      if (this.data.saler && this.data.saler.length === 0) return false
      let salerIsEditPrice = this.data.saler?this.data.saler[0].iseditprice:0
      if (this.data.type === '标准订单' && salerIsEditPrice && this.data.status === '新建') {
        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
    },
  },
  components:{
    excel:() =>  import('../details/export_excel'),
    addProduct,
    uploadAllData
  },
  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.currentPage = res.pageNumber
      console.log('成功',res.data);
      
      this.queryBasicInfo()
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.param.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": [row.sa_orderitemsid]
        },
      })
      this.tool.showMessage(res,()=>{
        this.listData()
        this.$emit('onSuccess')
      })
    },
    // async updateOrderProduct (val) {
    //   const res  = await this.$api.requested({
    //     "id": 20221110145302,
    //     "content": val
    //   })
    //   this.$emit('onSuccess')
    // },
    qtyChange (val,index) {
      let that = this
      this.$set(this.tableData,index,val)
      // // 防抖
      if(this.time !== null){
        clearTimeout(this.time);
      }
      this.time = setTimeout(() => {
        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.value2 = ''
      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 dateChange (row) {
      this.tableData = this.tableData.filter(e=>{
        if (e.delivery > 0) {
          e.needdate = this.value2
        }
        return e
      })
      const res = await this.$api.requested({
       "id": 20230104143802,
        "content": {
          "sa_orderid": this.$route.query.id, 
          "needdate": this.value2
        },
      })
    },
    async updateOrder (val,fn) {
      const res  = await this.$api.requested({
        "id": 20221109093602,
        "content": val
      })
      if (res.code == 1) {
        this.$emit('onSuccess')
        fn?fn():''
      } else {
        this.$message({
          type:'error',
          message:res.data + ':' + res.msg
        })
        this.listData()
      }
    },
    setPickerOptions (val) {
      var startDate = val.deliverydate
      startDate = startDate.replace(new RegExp("-","gm"),"/")
      var startDateM = (new Date(startDate)).getTime()
      this.pickerOptions = {
        disabledDate(time) {
          return time.getTime() < startDateM;
        },
      }
    },
    // 订单添加商品
    async onConfirm (data,edit,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:edit?e.sa_orderitemsid : 0,
                itemid:e.itemid,
                qty:e.orderminqty,
                needdate:e.deliverydate,
                remarks:e.remarks
              }
            })
          },
        })
      }
      this.listData()
      this.$emit('onSuccess')
    },
    inputChange (row,index) {
      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
      },()=>{
         this.$set(this.tableData,index,row)
      })
    },
    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 = []
    },
    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
      }
    },
  },
  mounted () {
    this.listData()
    console.log("表结构")
    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
  },
  watch:{
    value2 (val) {
      console.log(val)
    }
  }
}

</script>
<style>
</style>