<script setup lang="ts">
import { ref } from "vue"
import { statusOptions } from "./../config/_options"
import { httpFeedbackProducts, httpMakePlan, httpPlans } from "/@/api/sellOut/project";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";

import { addition, multiplication  } from "/@/utils/calc";
import { ElMessage } from "element-plus"
import { useTask } from "/@/hooks/core"


const props = defineProps<{ detail: any }>()

const state = ref({ 
  type: 'preview',
  selected: [],
  plans: [],
  data: [], 
  total: 0,
  index: 0
})

const productsTask = useTask({ success:(data) => {
  state.value.data = data.list
  requestPlans()
}})

const plansTask = useTask({ success: (data = []) => {
  state.value.plans = data
  state.value.index = 0
  state.value.selected = (data[state.value.index] || {}).feedback || []
  calcPlanTotalPrice()
} })

const requestPlans = () => plansTask.run(httpPlans({ projectNo: props.detail.projectNo }))
const makePlanTask = useTask({ success: () => {
  state.value.type = 'preview'
  requestPlans()
} })

function calcPlanTotalPrice(){
  state.value.total = state.value.selected.reduce((prev, { sale_price, num }) => {
    const current = Number(multiplication(sale_price, num)).toFixed(2)
    return Number(addition(prev, current)).toFixed(2) 
  }, 0)
}

function handleMoveIndex(step: number){
  state.value.index += step  
  state.value.selected = (state.value.plans[state.value.index] || {}).feedback || []
  calcPlanTotalPrice()
}

/* 选择意向商品 */ 
function handleSelectionChange(list: any[]){
  state.value.selected = []
  for(const item of list){
    const origin_sale_price = item.sale_price
    const new_sale_price = item.sale_price
    const origin_num = item.num
    state.value.selected.push({ ...item, origin_sale_price, new_sale_price, origin_num })
  }
}
/* 单机添加方案句柄 */
function handleCreateProject(){
  state.value.selected = []
  const { low_rate } = props.detail
  const rate = low_rate || '0'
  if(rate * 100 === 0){
    ElMessage.warning('暂无项目毛利率，不能制定方案！')
    return
  }
  state.value.type = 'create'
}
/* 单击保存方案的句柄 */
function onCrateProject(){
  const { selected } = state.value
  let isOnly = true
  for(const source of selected){
    const item = selected.find(target => target.pgNo === source.pgNo && target.id !== source.id)
    if(item) isOnly = false
  }
  if(!isOnly){
    ElMessage.warning('一种商品要求只能选择一种商品!')
    return
  }

  let isAll = true
  for(const source of props.detail.ladder){
    let to = 0
    selected.forEach(target => { if(source.pgNo === target.pgNo) to++ })
    if(to !== 1) isAll = false
  }
  if(!isAll){
    ElMessage.warning('方案必须覆盖全部商品要求!')
    return
  }

  const parameter = { feedback: [],  projectNo: props.detail.projectNo }
  selected.forEach(item => parameter.feedback.push({
    feedid: item.id,
    good_num: item.num,
    sale_price: item.new_sale_price
  }))

  makePlanTask.run(httpMakePlan(parameter))
}


/* 单击返回列表的句柄 */
function handleBacklist(){
  state.value.type = 'preview'
  requestPlans()
}

function initialData(){
  const parameter = { 
    page: 1, 
    size: 1000, 
    zxNo: '', 
    infoNo: '', 
    bidNo: '', 
    status: '1', 
    pgNo: '', 
    projectNo: props.detail.projectNo 
  }
  productsTask.run(httpFeedbackProducts(parameter))
}


initialData()
</script>

<template>
  <div v-if="detail" v-loading="makePlanTask.loading || plansTask.loading">
    <ElCard>
      <div class="flex flex-col">
        <!-- 商品要求-start -->
        <h1 class="mb-[10px]">商品要求</h1>
        <template v-if="detail.ladder">
          <ElTable :data="detail.ladder" :size="'small'" border stripe style="width: 100%">
            <ElTableColumn label="要求编码" prop="pgNo" width="155px" show-overflow-tooltip />
            <ElTableColumn prop="good_type" label="商品类型" width="80px" show-overflow-tooltip>
              <template #="{ row }">
                <ElTag :size="'mini'">
                  {{ (statusOptions.find((item) => item.value == row.good_type) || {}).label || '--' }}
                </ElTag>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="budget_price" label="预算单价" width="110" show-overflow-tooltip />
            <ElTableColumn prop="num" label="购买数量" width="110" show-overflow-tooltip />
            <ElTableColumn prop="cat_name" label="商品分类" show-overflow-tooltip />
            <ElTableColumn prop="good_img" label="图片" width="50" show-overflow-tooltip>
              <template #="{ row }">
                <ElImage 
                  v-if="row.good_img"
                  style="height:20px;width:20px"
                  :teleported="true"
                  :url-list="[row.good_img]"
                  :src="row.good_img"
                />
              </template>
            </ElTableColumn>
            <ElTableColumn prop="good_name" label="商品名称" show-overflow-tooltip />
          </ElTable>
        </template>
        <!-- 商品要求-end -->

        <!-- 客户意向商品-start -->
        <h1 class="my-[10px]">客户意向商品</h1>
        <ElTable
          border
          stripe
          :size="'small'"
          ref="multipleTable"
          style="width: 100%"
          :data="state.data"
          @selection-change="handleSelectionChange"
          v-loading="productsTask.loading"
        >
          <ElTableColumn type="selection" width="40" v-if="state.type === 'create'"></ElTableColumn>
          <ElTableColumn prop="pgNo" label="要求编码" width="155px" show-overflow-tooltip />
          <ElTableColumn prop="sale_price" label="销售单价" width="110" show-overflow-tooltip />
          <ElTableColumn prop="num" label="购买数量" width="110" show-overflow-tooltip />
          <ElTableColumn prop="good_img" label="商品图片" min-width="168px" show-overflow-tooltip>
            <template #="{ row }">
                <ElImage 
                  v-if="row.good_img"
                  style="height:20px;width:20px"
                  :teleported="true"
                  :url-list="[row.good_img]"
                  :src="row.good_img"
                />
              </template>
          </ElTableColumn>
          <ElTableColumn prop="good_name" label="商品名称" min-width="120" show-overflow-tooltip>
            <template #="{ row }">
              <span>{{ row.good_name }}</span>
              <span
                v-for="(si, sii) in row.specinfo"
                :key="si.id + sii"
              >{{ sii === 0 ? "_" : "-" }}{{ si.spec_name }}[{{ si.spec_value_name }}]</span>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="data_source" label="商品类型" width="85" show-overflow-tooltip>
            <template #="{ row }">
              <ElTag :size="'mini'" :type="row.data_source + '' === '1' ? 'success' : ''">
                {{ row.data_source + '' === "1" ? "平台商品" : "采反商品" }}
              </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="class_cat" label="商品分类" show-overflow-tooltip />
          <ElTableColumn prop="expire_day" label="信息有效期" width="85" show-overflow-tooltip />
          <ElTableColumn prop="work_day" label="制作工期" width="70" show-overflow-tooltip />
          <ElTableColumn prop="delivery_day" label="物流时间" width="70" show-overflow-tooltip />
        </ElTable>
        <!-- 客户意向商品-end -->

        <!-- 项目方案-start -->
        <div class="my-[10px] flex justify-between">
          <h1 class="flex">
            项目方案
            <p v-if="state.type !== 'create' && state.plans.length !== 0" class="ml-[20px] color-red">
              方案总金额: {{ state.total }}
            </p>
          </h1>

          <ElButtonGroup  type="primary">
            <ElButton v-if="state.type !== 'create'" :icon="useRenderIcon('add')" @click="handleCreateProject">
              添加方案
            </ElButton>

            <template v-else>
              <ElButton :icon="useRenderIcon('arrow-left-s-line')" @click="handleBacklist">
               返回列表
              </ElButton>
              <ElButton @click="onCrateProject">
                保存方案
              </ElButton>
            </template>

            <template v-if="state.plans.length !== 0 && state.type !== 'create'">
              <ElButton 
                :icon="useRenderIcon('arrow-left-s-line')"
                :disabled="state.index === 0"
                @click="handleMoveIndex(-1)"
              />
              <ElButton>方案共{{ state.index + 1 }}/{{ state.plans.length }}</ElButton>
              <ElButton 
                :icon="useRenderIcon('arrow-right-s-line')"
                :disabled="state.index === state.plans.length - 1"
                @click="handleMoveIndex(1)"
              />
            </template>
          </ElButtonGroup>
        </div>

        <ElTable
          :data="state.selected" 
          style="width: 100%"
          :size="'small'"
          border
          stripe
        >
          <ElTableColumn prop="pgNo" label="要求编码" width="155px" show-overflow-tooltip />
          <ElTableColumn
            prop="origin_sale_price"
            label="系统售价单价"
            width="110"
            show-overflow-tooltip
          />

          <ElTableColumn prop="new_sale_price" label="当前销售单价" width="150" show-overflow-tooltip>
            <template #="{ row, $index }">
              <ElInputNumber 
                v-if="state.type === 'create'"
                v-model="state.selected[$index].new_sale_price"
                :min="0"
                :precision="2"
                placeholder="售价"
                :max="100000000000"
                controls-position="right"
                size="small"
              />

              <span v-else>{{ row.new_sale_price || row.sale_price }}元</span>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="origin_num" label="竞价数量" width="130" show-overflow-tooltip />
          <ElTableColumn prop="num" label="购买数量" width="150" show-overflow-tooltip>
            <template #="{ row, $index }">
              <ElInputNumber 
                v-if="state.type === 'create'"
                 v-model="state.selected[$index].num"
                controls-position="right"
                placeholder="购买数量"
                :max="100000000000"
                :precision="0"
                size="small"
                :min="row.origin_num"
              />
              <span v-else>{{ row.num }}</span>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="data_source" label="商品类型" width="85">
            <template #="{ row }">
              <ElTag
                :size="'mini'"
                :type="row.data_source + '' === '1' ? 'success' : ''"
              >{{ row.data_source + '' === "1" ? "平台商品" : "采反商品" }}
            </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="good_img" label="商品图片" min-width="242px" show-overflow-tooltip>
            <template #="{ row }">
              <ElImage 
                v-if="row.good_img"
                style="height:20px;width:20px"
                :teleported="true"
                :url-list="[row.good_img]"
                :src="row.good_img"
              />
            </template>
          </ElTableColumn>
          <ElTableColumn prop="good_name" label="商品名称" min-width="120" show-overflow-tooltip>
            <template #="{ row }">
              <span>{{ row.good_name }}</span>
              <span v-for="(si, sii) in row.specinfo"  :key="si.id + sii">
                {{ sii === 0 ? "_" : "-" }}{{ si.spec_name }}[{{ si.spec_value_name }}]
              </span>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="class_cat" label="商品分类" show-overflow-tooltip />
        </ElTable>
        <!-- 项目方案-end -->
      </div>
    </ElCard>
  </div>
</template>
