<script setup lang="ts">
import { ref, nextTick } from "vue"
import { httpOnlineProduct, httpActivity, httpMinimumPrice } from "/@/api/sellOut/salesOrder";
import { basicRules, productDetailColumns, goodTypeOptions2 } from "./../config/_options"
import BasicDescriptions from "/@/components/BasicDescriptions";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import UploadAddress from "./upload-address/index.vue"
import ProductModal from "./ProductModal/index.vue"
import { useCurrentCompany } from "/@/hooks/core"
import { ElMessage, ElForm } from "element-plus"
import ProofModal from "./ProofModal/index.vue"
import AddressModal from "./AddressModal.vue"
import { tryOnMounted } from "@vueuse/core"

import { BusinessQuery, CustomerQuery, PlatformQuery, ManagerQuery, OrderUsedQuery } from "/@/components/BasicForm"
import { UnitInput, NumberInput } from "/@/components/Input"
import { cloneDeep } from "lodash-unified";


const { current } = useCurrentCompany()
const formRef = ref<InstanceType<typeof ElForm> | null>(null)
const goodTypeOptionsRef = ref(cloneDeep(goodTypeOptions2))
const sendTypeOptions = [{ value: '1', label: '有地址下单' }, { value: '2', label: '无地址下单' }]


const state = ref({ 
  batchModalVisible: false,  /** 批量上传收货地址模态框显示状态 */ 
  addressModalVisible: false, /** 收货地址模态框显示状态 */ 
  index: -1,  /** 收货地址当前编辑项的索引 -1为创建 */ 
  data: {}, /** 收货地址便编辑当前项的初始值 */
  productModalVisible: false, /** 选择商品模态框显示状态 */
  productDetail: {}, /** 商品详情数据 */
  proofModalVisible: false, /** 凭证模态框显示状态 */
  platformType: '' /** 当前平台的对接类型  1为有赞 2 为BBC */
})

const formData = ref({
  new_good_price: '0',
  activity_stock: '0',
  good_price: '0',
  good_num: '0',
  remark: '',
  useid: '',

  platform_order: '',
  customer_code: '',
  platform_id: '',
  proof_type: '',
  sell_code: '',
  managerid: '',
  proof_url: '',
  good_code: '',
  proof_id: '',
  goodtype: '',
  spuCode: '',
  paytime: '',
  workNo: '',
  addr: []
})

const orderGoodNum = ref({
  ogood_type: "",
  ogood_num: '0'
})

function handleGoodChange(){
  if(!formData.value.platform_id){
    ElMessage.warning('请先选择平台')
    return
  }
  
  if(!formData.value.sell_code){
    ElMessage.warning('请选择销售方公司')
    return
  }
  
  if(state.value.platformType === '1'){
    ElMessage.warning('当前业务不支持对接有赞平台的商品')
    return
  }
  
  if(state.value.platformType === '2'){
    ElMessage.warning('当前业务不支持对接BBC平台的商品')
    return
  }

  state.value.productModalVisible = true
}

function handleAddress(row = {}, index){
  if(index === -1){
    formData.value.addr.push(row)
  }else{
    formData.value.addr[index] = { ...row }
  }
}

function handlePlatformChange(_, detail = ({} as any)){
  const { platform_type } = detail
  state.value.platformType = platform_type
}

function onDeleteAddress(index: number){
  formData.value.addr.splice(index ,1)
}

function onUpdateAddress(index: number){
  state.value.addressModalVisible = true
  state.value.index = index
  state.value.data = { ...formData.value.addr[index] }
}

function handleCreateAddress(){
  state.value.data = {}
  state.value.index = -1
  state.value.addressModalVisible = true
}

async function requestProductsActivity(){
  const { good_code, sell_code, platform_id } = formData.value

  const parameter = {
    supplierNo: sell_code,
    skuCode: good_code,
    platform_id
  }

  const { code, data, message } = await httpActivity(parameter)

  if(code == 0){
    const { act, good } = data
    const actlist = act.length > 0 ? JSON.parse(JSON.stringify(act)) : []

    actlist.forEach(item => {
      item.value = item.activity_code;
      item.label = item.activity_name;
    })

    goodTypeOptionsRef.value[1].children = []
    goodTypeOptionsRef.value[1].children.push(...actlist)
    const goodItem = good.length > 0 ? cloneDeep(good[0]) : {}

    if(goodItem.good_name){
      goodTypeOptionsRef.value[0].children.map(item => {
        item.activity_stock = goodItem ? String(goodItem.stock_num) : "0"
        return item
      })
    }
  }else{
    ElMessage.warning(message)
  }

}

async function handleProductSelection(product){
  formData.value = {
    ...formData.value,
    proof_id: '',
    proof_url: '',
    proof_type: '',
    spuCode: product.spuCode,
    good_code: product.skuCode
  }
  
  nextTick(() => formRef.value.validateField('good_code'))
  
  const result = await httpOnlineProduct({ skuCode: formData.value.good_code })
  state.value.productDetail = result.data
  requestProductsActivity()
}

async function requestMinimumPrice(){
  const result = { ok: true, price: '0' }
  const {  good_num, good_code, goodtype } = formData.value

  const key_1 = goodtype[1]
  const key_0 = goodtype[0]


  const parameter = { 
    skuCode: good_code,
    sale_num: good_num,
    is_activity: key_0 === "is_activity_0" ? "0" : "1",
    act_code: key_0 === "is_activity_1" ? key_1 : ""
  }


  const { code, message, data } = await httpMinimumPrice(parameter)


  if(code === 0){ 
    const { sale_price } = data
    result.price = sale_price + ""
    const oldGoodType = goodtype.length === 2 ? goodtype[1] : ""


    if(key_0 === 'is_activity_0' && (oldGoodType == 2 || oldGoodType == 3)){
      result.price = '0'
    }

  } else {
    result.ok = false
    ElMessage.warning(message)
  }

  return result
}

async function requestProductNewPrice(){
  const { goodtype, good_num } = formData.value
  const oldGoodType = goodtype.length === 2 ? goodtype[1] : ''
  
  if(oldGoodType == 2 || oldGoodType == 3){
    formData.good_price = 0
  }

  const { ogood_type, ogood_num } = orderGoodNum.value
  if(oldGoodType === ogood_type && good_num === ogood_num){
    this.order_good_num = { ogood_type: goodtype.length === 2 ? goodtype[1] : '', ogood_num: formData.value.good_num };
    return
  }

  if(goodtype.length === 2){
    goodTypeOptionsRef.value.forEach(item => {
      if(item.children && item.children.length){
        item.children.forEach(child => {
          if(child.value === goodtype[1]){
            formData.value.activity_stock = child.activity_stock
          }
        })
      }
    })
  } else {
    formData.value.activity_stock = "0"
  } 


  // 请求系统最低售价
  const result = await requestMinimumPrice()
  formData.value.good_price = result.ok ? result.price : 0
}

async function handleProductNumChange(num){
  if(Number(num || '0') !== 0){
    await requestProductNewPrice()
    await requestProductsActivity()
  }

}

function handleProductTypeChange(){


  
}


async function submitForm(){
 try {
  await formRef.value?.validate()
  const { addr } = formData.value

  if(addr.length === 0 && sendtype === '1'){
    ElMessage.warning('至少填写一条地址信息')
    return
  }

 } catch(err) {
  console.log(err)
 }
}


tryOnMounted(() => {
  formData.value.sell_code = current.value.companyNo
})
</script>

<template>
  <ElForm :rules="basicRules" ref="formRef" :model="formData">
    <ElRow :gutter="10">
      <ElCol :span="12">
        <ElFormItem label="销售方" prop="sell_code">
          <BusinessQuery 
            v-model="formData.sell_code" 
            placeholder="销售方公司" 
            disabled 
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="12">
        <ElFormItem label="企业客户" prop="customer_code">
          <CustomerQuery 
            v-model="formData.customer_code" 
            placeholder="企业客户" 
          />
        </ElFormItem>
      </ElCol>
    </ElRow>

    <ElRow :gutter="10">
      <ElCol :span="6">
        <ElFormItem label="所属平台" prop="platform_id">
          <PlatformQuery 
            v-model="formData.platform_id" 
            placeholder="所属平台"
            @change="handlePlatformChange"
          />
        </ElFormItem>
      </ElCol>
  
      <ElCol :span="6">
        <ElFormItem label="平台订单号" prop="platform_order">
          <ElInput 
            v-model="formData.platform_order" 
            placeholder="如: PO号" 
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="回款时间" prop="paytime">
          <ElDatePicker 
            style="width: 100%"
            v-model="formData.paytime" 
            placeholder="回款时间"
            :disabledDate="time => time.getTime() < Date.now() - 100 * 60 * 60 * 24"
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="6">
        <ElFormItem label="其他单号" prop="workNo">
          <ElInput v-model="formData.workNo" placeholder="其他单号" />
        </ElFormItem>
      </ElCol>
    </ElRow>

    <ElRow :gutter="10">
      <ElCol :span="12">
        <ElFormItem label="销售商品" prop="good_code">
          <ElInput
            v-if="!formData.good_code"
            placeholder="销售商品" 
            @click="handleGoodChange"
            v-model="formData.good_code"
            readonly
          />

          <BasicDescriptions 
            v-else
            :data="state.productDetail"
            :columns="productDetailColumns"
          />
        </ElFormItem>
      </ElCol>

      <ElCol :span="12">
        <ElRow :gutter="10">
          <template v-if="formData.good_code">
            <ElCol :span="12">
              <ElFormItem label="活动类型" prop="goodtype">
                <ElCascader
                  v-model="formData.goodtype"
                  :options="goodTypeOptionsRef"
                  style="width: 100%"
                  :props="{ expandTrigger: 'hover' }"
                  @change="handleProductTypeChange"
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="12">
              <ElFormItem label="比价凭证" prop="proof_id">
                <div class="w-full flex justify-between">
                  <ul>
                    暂无凭证
                  </ul>

                  <ElTooltip content="查看历史凭证">
                    <ElButton 
                      type="primary" 
                      size="small" 
                      link 
                      :icon="useRenderIcon('search')"
                      @click="state.proofModalVisible = true"
                    />
                  </ElTooltip>
                </div>
              </ElFormItem>
            </ElCol>

            <ElCol :span="12">
              <ElFormItem label="剩余库存" prop="activity_stock">
                <NumberInput v-model="formData.activity_stock" disabled />
              </ElFormItem>
            </ElCol>

            <ElCol :span="12">
              <ElFormItem label="系统最低售价" prop="good_price">
                <UnitInput unit="元" v-model="formData.good_price" disabled />
              </ElFormItem>
            </ElCol>

            <ElCol :span="12">
              <ElFormItem label="销售数量" prop="good_num">
                <NumberInput 
                  v-model="formData.good_num" 
                  @change="handleProductNumChange"
                />
              </ElFormItem>
            </ElCol>

            <ElCol :span="12">
              <ElFormItem label="销售单价" prop="new_good_price">
                <NumberInput 
                  v-model="formData.new_good_price" 
                  :disabled="formData.good_price == '0'"
                />
              </ElFormItem>
            </ElCol>
          </template>

          <ElCol :span="24">
            <ElFormItem label="业务经理" prop="managerid">
              <ManagerQuery
                placeholder="业务经理" 
                v-model="formData.managerid"
                :companyNo="current.companyNo" 
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="到货时间" prop="arrtime">
              <ElDatePicker 
                v-model="formData.arrtime" 
                placeholder="到货时间"
                style="width: 100%"
              />
            </ElFormItem>
          </ElCol>

          <ElCol :span="12">
            <ElFormItem label="下单方式" prop="sendtype">
              <ElSelect
                v-model="formData.sendtype"
                style="width: 100%" 
                placeholder="下单方式"
              >
                <ElOption 
                  v-for="opt in sendTypeOptions"
                  :value="opt.value"
                  :label="opt.label"
                  :key="opt.value"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElFormItem label="订单用途" prop="useid">
              <OrderUsedQuery v-model="formData.useid" placeholder="订单用途" />
            </ElFormItem>
          </ElCol>


          <ElCol :span="24" v-if="formData.good_code">
            <ElFormItem label="订单备注" prop="remark">
              <ElInput
                v-model="formData.remark"
                type="textarea" 
                placeholder="订单备注" 
                :rows="3" 
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElCol>
    </ElRow>

    <ElRow v-if="!formData.good_code">
      <ElCol :span="24">
        <ElFormItem label="订单备注" prop="remark">
          <ElInput 
            v-model="formData.remark" 
            placeholder="订单备注"
            type="textarea" 
          />
        </ElFormItem>
      </ElCol>
    </ElRow>


    <ElRow>
      <ElCol :span="24">
        <ElTable border size="small" :data="formData.addr">
          <ElTableColumn label="收货总数" min-width="80px" prop="receipt_quantity" />
          <ElTableColumn label="收货联系人" min-width="180px" prop="contactor" />
          <ElTableColumn label="收货联系电话" width="180px" prop="mobile" />
          <ElTableColumn label="收货省市区" min-width="180px" prop="addr_name" />
          <ElTableColumn label="详细地址" min-width="180px" prop="addr" />
          <ElTableColumn width="100px">
            <template #header>
              <!-- <ElTooltip content="下载收货地址模板" placement="top">
                <ElButton size="small" link type="primary" :icon="useRenderIcon('arrow-down-line')" />
              </ElTooltip>
              <ElTooltip content="导入收货地址" placement="top">
                <ElButton
                  link 
                  size="small" 
                  type="primary" 
                  :icon="useRenderIcon('arrow-up-line')"
                  @click="state.batchModalVisible = true"
                />
              </ElTooltip> -->
              <ElTooltip content="手动添加地址" placement="top">
                <ElButton 
                  link 
                  size="small" 
                  type="primary" 
                  :icon="useRenderIcon('add')" 
                  @click="handleCreateAddress" 
                />
              </ElTooltip>
            </template>

            <template #="{ row, $index }">
              <ElTooltip content="修改" placement="top">
                <ElButton 
                  link 
                  type="primary" 
                  :icon="useRenderIcon('edits')" 
                  @click="onUpdateAddress($index)" 
                />
              </ElTooltip>

              <ElTooltip content="删除" placement="top">
                <ElButton 
                  link 
                  type="danger" 
                  :icon="useRenderIcon('delete')" 
                  @click="onDeleteAddress($index)" 
                />
              </ElTooltip>
            </template>
          </ElTableColumn>
        </ElTable>
      </ElCol>
    </ElRow>

    <ElRow>
      <div class="w-full flex justify-between mt-[10px]">
        <p class="font-bold">订单总金额: 0</p>
        <ElButton type="primary" @click="submitForm">保存</ElButton>
      </div>
    </ElRow>

    <AddressModal 
      v-model:visible="state.addressModalVisible"  
      :index="state.index" 
      :data="state.data"
      @submit="handleAddress"
    />

    <ProductModal 
      v-model:visible="state.productModalVisible"
      :platformCode="formData.platform_id"
      @submit="handleProductSelection"
    />

    <ProofModal  
      v-model:visible="state.proofModalVisible" 
      :spuCode="formData.spuCode"
    />
    
    <UploadAddress 
      v-model:visible="state.batchModalVisible" 
    />
  </ElForm>
</template>
