<template>
  <div>
    <detail-template :headData="mainAreaData" :title="'订单号:'+orderData.sonum" :tabs="['订单明细','订单进度','发货单','收支明细']" :delParam="{id:'20221108152102',content:{sa_orderids:[router.currentRoute.value.query.id]}}" :disable="utils.isDisabled(orderData.status,['提交','审核','关闭','预提交','确认'])" size="small" :hideBorder="false" ownertable="sa_order">
      <template #operation>
        <a-space>
          <edit v-if="utils.hasPermission('update')" :data="orderData" @onSuccess="mianData" :disabled="utils.isDisabled(orderData.status,['提交','审核','关闭'],specialOrder('编辑'))"></edit>
          <a-button v-if="orderData.type === '特殊订单' && utils.hasPermission('preSubmission')" type="primary" @click="preSubmission" :disabled="utils.isDisabled(orderData.status,['提交','审核','关闭','预提交','确认'])">预提交</a-button>
          <a-button v-if="utils.hasPermission('submit')" type="primary" @click="submitOrder" :disabled="utils.isDisabled(orderData.status,['提交','审核','关闭'],(specialOrder('提交')))">提交</a-button>
          <!-- <a-button type="primary" @click="backOrder" :disabled="utils.isDisabled(orderData.status,['新建','审核','关闭'],specialOrder('撤回'))">撤回</a-button> -->
        </a-space>
      </template>
      <template #tab0>
        <div class="flex">
          <a-space class="mt-10">
            <!-- 添加产品 -->
            <select-product v-if="utils.hasPermission('orderDetail')" :disabled="utils.isDisabled(orderData.status,['提交','审核','关闭'],specialOrder('编辑'))" :param="listParam" @onSelect="addProductToBody">
              <template #tb_cell="{data}">
                <div v-if="data.column.dataIndex === 'qty'">
                  <a-input-number style="width:100%" id="inputNumber" v-model:value="data.record.qty" :min="data.record.orderminqty" :step="data.record.orderaddqty"/>
                </div>
              </template>
            </select-product>
            <a-button v-if="utils.hasPermission('orderDetail')" :disabled="utils.isDisabled(orderData.status,['提交','审核','关闭'],(selectProductList.length == 0 || specialOrder('编辑')))" type="primary" @click="deleteProd">删除产品</a-button>
          </a-space>
        </div>
        <product-list :loading="loading" ref="prodlist" :columns="columns" :param="param" size="small" @onSelect="onProdSelect">
          <template #operation>
            <a-input class="search-input" v-model:value="param.content.where.condition" @keyup.enter="onSearch" placeholder="搜索产品"></a-input>
          </template>
          <template #tb_cell="{data}">
            <template v-if="data.column.dataIndex === 'qty'">
              <a-input-number style="width:100%" id="inputNumber" :disabled="utils.isDisabled(orderData.status,['提交','审核','关闭'],specialOrder('编辑'))" v-model:value="data.record.qty" :min="data.record.orderminqty" :step="data.record.orderaddqty" @change="inputChange(data.record)"/>
            </template>
            <template v-if="data.column.dataIndex === 'remarks'">
              <a-input style="width:100%" :disabled="utils.isDisabled(orderData.status,['提交','审核','关闭'],specialOrder('编辑'))" v-model:value="data.record.remarks" :min="1" @change="inputChange(data.record)" placeholder="请输入产品备注"/>
            </template>
            <template v-if="data.column.dataIndex === 'defaultprice'">
              {{utils.formatAmount(data.record.defaultprice)}}
            </template>
            <template v-if="data.column.dataIndex === 'price'">
              {{utils.formatAmount(data.record.price)}}
            </template>
             <template v-if="data.column.dataIndex === 'amount'">
              {{utils.formatAmount(data.record.amount)}}
            </template>
          </template>
        </product-list>
      </template>
      <template #tab1>
        <od-progress></od-progress>
      </template>
      <template #tab2>
        <dispatch-temp></dispatch-temp>
      </template>
      <template #tab3>
        <income-mx></income-mx>
      </template>
    </detail-template>
  </div>
</template>

<script setup>
import Api from '@/api/api'

import productList from '@/template/billProductTable/index.vue'
import SelectProduct from '@/template/selectProduct/index.vue'
import detailTemplate from '@/components/detailTemplate/index.vue'
import edit from './modules/edit.vue'
import OdProgress from './tabs/progress.vue'
import DispatchTemp from './tabs/dispatch.vue'
import IncomeMx from './tabs/income.vue'
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { useRouter } from "vue-router"
import { onMounted,ref,getCurrentInstance,createVNode,computed} from "vue"
import utils from '@/utils/utils'
const router = useRouter()
const mainAreaData = ref([])
const param = ref({
  "id": 20221109093902,
  "content": {
    "sa_orderid": router.currentRoute.value.query.id, //订单ID
    "pageNumber": 1,
    "pageSize": 20,
    "where": {
      "condition": ""
    }
  },
})
const loading = ref(false)
let time = ref(null)
const prodlist = ref(null);
const orderData = ref({})
const selectProductList = ref([])
const listParam = computed(()=>{
  let params = {id:0,content:{sa_orderid:orderData.sa_orderid,pageNumber:1,pageSize:20,where:{condition:''}}}
  switch (orderData.value.type) {
    case '标准订单':
      params.id = 20221109153502
      break;
    case '项目订单':
      params.id = 20230103155002
      break;
    case '促销订单':
      params.id = 20230107182302
      break;
    case '工具订单':
      params.id = 20221109153502
      break;
    default:
      params.id = 20221109153502
      break;
  }
  return params
})
const specialOrder = (btn)=>{
  if (orderData.value.type === '特殊订单') {
    if (orderData.value.status === '确认' && btn === '提交') {
      return false
    } else if (orderData.value.status === '预提交') {
      return true
    } else if (orderData.value.status === '新建' && btn === '编辑'){
      return false
    } else {
      return true
    }
  } else {
    return false
  }
}
const mianData = async ()=>{
  const res = await Api.requested({
    "id":'20221108151302',
    "content": {
      "nocache":true,
      "sa_orderid": router.currentRoute.value.query.id
    }
  })
  orderData.value = res.data
  changeDataStructure(res.data)
}
const changeDataStructure = (data) => {
  mainAreaData.value = [
    {
      label:'订单状态',
      value:data.status,
      style:function() {
        let style = {}
        switch (data.status) {
          case '新建':
            style = {color:"#000000"}
            break;
          case '提交':
            style = {color:"#d90a0a"}
            break;
          case '交期待确认':
            style = {color:"#e09a1a"}
            break;
          case '交期确认':
            style = {color:"#3874f6"}
            break;
          case '审核':
            style = {color:"#52C41A"}
            break;
          case '关闭':
            style = {color:"#b2c0ea"}
            break;
          default:
            break;
        }
        return style
      },
    },
    {
      label:'订单类型',
      value:data.type,
    },
    {
      label:'明细分类',
      value:data.typemx,
    },
    {
      label:'单据日期',
      value:data.billdate,
    },
    {
      label:'企业名称',
      value:data.enterprisename,
    },
    {
      label:'订单金额',
      value:utils.formatAmount(data.defaultamount),
    },
    {
      label:'折后金额',
      value:utils.formatAmount(data.amount),
    },
    {
      label:'合计数量',
      value:data.qty,
    },
    {
      label:'领域',
      value:data.tradefield,
    },
    {
      label:'业务员',
      value:data.saler_name,
    },
    {
      label:'开票单位',
      value:data.finance.enterprisename,
    },
    {
      label:'支付账户',
      value:data.accountclass.accountname,
    },
    {
      label:'账户余额',
      value:data.accountclass.balance
    },
    {
      label:'信用额度',
      value:data.accountclass.creditquota
    },
    {
      label:'退回原因',
      value:data.backreason,
      span:4
    },
    {
      label:'备注',
      value:data.remarks,
      span:6
    },
  ]
}
const updateProd = async (data,msg) =>{
  loading.value = true
  const res = await Api.requested({
    id:20221109093602,
    content:{
      sa_orderid:orderData.value.sa_orderid,
      sys_enterpriseid:orderData.value.sys_enterpriseid,
      type:orderData.value.type,
      items:data
    }
  })
  utils.message(res,msg,()=>{
    mianData()
   
  })
  prodlist.value.listData()
  loading.value = false
}
const addProductToBody = async (val) =>{
  let data = val.map(e=>{
    return {
      sa_orderitemsid:0,
      itemid:e.itemid,
      qty:e.qty
    }
  })
  updateProd(data,'添加成功',()=>{
    prodlist.value.tableRecord = []
  })
}
const inputChange = (val) =>{
  let data = [{
    sa_orderitemsid:val.sa_orderitemsid,
    itemid:val.itemid,
    qty:val.qty,
    remarks:val.remarks
  }]
  if(time !== null){
    clearTimeout(time);
  }
  time = setTimeout(() => {
    updateProd(data,'修改成功')
  },500)
}
const onProdSelect = (val) => {
  selectProductList.value = val
}
const deleteProd = ()=>{
  console.log(selectProductList.value)
  Modal.confirm({
    title: '删除产品',
    icon: createVNode(ExclamationCircleOutlined),
    content: `当前选中${selectProductList.value.length}个产品,删除${selectProductList.value.length}个产品!`,
    async onOk() {
      loading.value = true
      const res = await Api.requested({
        id:20221109093702,
        content:{
          sa_orderid:orderData.value.sa_orderid,
          sa_orderitemsids:selectProductList.value.map(e=>{
            return e.sa_orderitemsid
          })
        }
      })
      utils.message(res,'删除成功',()=>{
        loading.value = false
        prodlist.value.selectedRowKeys = []
        prodlist.value.tableRecord = []
        selectProductList.value = []
        prodlist.value.listData()
        mianData()
      })
    },
    onCancel() {},
  });
  
}
const submitOrder = ()=>{
  Modal.confirm({
    title: '提交订单',
    icon: createVNode(ExclamationCircleOutlined),
    content: `确认提交该订单吗!`,
    async onOk() {
      const res = await Api.requested({
        "id": 20221108153402,
        "content": {
          "sa_orderid": orderData.value.sa_orderid,
          "sys_enterpriseid": orderData.value.sys_enterpriseid,
          "sa_accountclassid": orderData.value.sa_accountclassid
        },
      })
      utils.message(res,'提交成功',()=>{
        mianData()
      })
    },
    onCancel() {},
  });
}
const backOrder = ()=>{
  Modal.confirm({
    title: '撤回订单',
    icon: createVNode(ExclamationCircleOutlined),
    content: `确认撤回该订单吗!`,
    async onOk() {
      const res = await Api.requested({
        "id": 20230301190202,
        "content": {
          "sa_orderid": orderData.value.sa_orderid,
        },
      })
      utils.message(res,'撤回成功',()=>{
        mianData()
      })
    },
    onCancel() {},
  });
}
const preSubmission = async ()=> {
  Modal.confirm({
    title: '预提交订单',
    icon: createVNode(ExclamationCircleOutlined),
    content: `确认预提交该订单吗!`,
    async onOk() {
      const res = await Api.requested({
        "id": 20230331152503,
        "content": {
          "sa_orderid": orderData.value.sa_orderid,
          "isrecheck":true
        },
      })
      utils.message(res,'预提交成功',()=>{
        mianData()
      })
    },
    onCancel() {},
  });
}
const onSearch = ()=>{
  param.value.content.pageNumber = 1
  prodlist.value.listData()
}
const columns = [
  {
    title:'行号',
    dataIndex:'rowno',
    width:90,
    ellipsis:true,
    fixed:true
  },
  {
    title:'产品名称',
    dataIndex:'itemname',
    width:180,
    ellipsis:true,
    fixed:true
  },
  {
    title:'产品编号',
    dataIndex:'itemno',
    width:180,
    ellipsis:true,
    fixed:true
  },
  {
    title:'型号',
    dataIndex:'model',
    width:180,
    ellipsis:true,
    fixed:true
  },
  {
    title:'数量',
    dataIndex:'qty',
    width:120,
    ellipsis:true,
  },
  {
    title:'原价',
    dataIndex:'defaultprice',
    width:180,
    ellipsis:true,
  },
  {
    title:'单价',
    dataIndex:'price',
    width:180,
    ellipsis:true,
  },
  {
    title:'金额',
    dataIndex:'amount',
    width:180,
    ellipsis:true,
  },
  {
    title:'包装数量',
    dataIndex:'packageqty',
    width:180,
    ellipsis:true,
  },
  {
    title:'未发货数量',
    dataIndex:'undeliqty',
    width:180,
    ellipsis:true,
  },
  {
    title:'备注',
    dataIndex:'remarks',
    width:360,
    ellipsis:true,
  }
]
onMounted (()=>{
  mianData()
  
})
</script>
<style scoped>
  .flex{
    display: flex;
  }
  .search-input{
    width: 300px;
    margin-bottom: 20px;
  }
</style>
