<script setup lang="ts">
import { ref, watch, reactive, computed } from "vue"
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { BusinessQuery, PlatformQuery, CustomerQuery } from "/@/components/BasicForm";
import { rules, goodTypeOptions } from "./../config/_options"
import { useCompany } from "/@/hooks/core/useCompany";
import { httpCreate } from "/@/api/sellOut/project";
import { ElForm, ElMessage } from "element-plus"

import { useRouter } from "vue-router"

import LadderModal from "./ladderModal.vue"


const props = defineProps<{ detail?: any }>()
const type = computed(() => props.detail ? 'detail' : 'create')
const { currentCompany } = useCompany()

const initialData = {
  name: '', // 项目名称
  platform: '', // 所属平台
  companyNo: '', // 销售方
  khNo: '', // 购买方
  budget_total: '0.00', // 项目总预算
  arrtime: '', // 要求到货时间
  endtime: '', // 竞价截止时间
  use_desc: '', // 竞价截止时间
  ladder: [] // 商品要求
}

const loading = ref(false)
const router = useRouter()
const data = ref({ ...initialData })
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

const ladderTemp = reactive({
  visible: false,
  type: 'create',
  index: -1,
  detail: {}
})


watch(
  () => currentCompany,
  () => {
    if (!currentCompany && type.value === 'create') { return  }
    data.value.companyNo = currentCompany.value.companyNo
  },
  { immediate: true, deep: true }
)

watch(() => type.value, () => {
  if(type.value === 'create') { return }
  data.value = { ...props.detail }
}, {
  immediate: true
})

const disabledDate = (time) => time.getTime() < Date.now() - 1000 * 60 * 60 * 24

async function submit() {
  try {
    formRef.value && formRef.value.validate()
    let { ladder, ...rest } = data.value

    if(ladder.length < 2){
      ElMessage.warning('至少添加两条项目要求')
      return 
    }

    ladder = ladder.map(({ can, ...rest }) => ({
      ...rest,
      cat_id: can.length === 3 ? can[2].id : ''
    }))

    loading.value = true
    const { code, message } = await httpCreate({ ...rest, ladder })
    loading.value = false

    if(Number(code) === 0){
      router.push('/sellOut/project')
    } else {  
      ElMessage.error(message)
    }

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

function onAddLadder() {
  ladderTemp.visible = true
  ladderTemp.type = 'create'
  ladderTemp.index = -1
  ladderTemp.detail = { budget_total: '', good_name: '', good_type: '', good_img: '', can: [], num: 0 }
}

function onUpdateLadder(index: number){
  ladderTemp.visible = true
  ladderTemp.type = 'update'
  ladderTemp.index = index
  const { can, ...rest } = data.value.ladder[index]!
  ladderTemp.detail = { ...rest, can: can.map(({id}) => id)}
}

function handleLadderAdd(item) {
  data.value.ladder.push(item)
}

function handleLadderUpdate(options:any){
  data.value.ladder[options.index] = options.data
}
</script>

<template>
  <div style="width:100%">
    <ElForm label-width="100px" size="small" :rules="rules" ref="formRef" :model="data" v-loading="loading" :disabled="type !== 'create'">
      <ElRow :gutter="10">
        <ElCol :span="12">
          <ElFormItem label="项目名称" prop="name">
            <ElInput v-model="data.name" placeholder="项目名称" />
          </ElFormItem>
        </ElCol>
        
        <ElCol :span="12">
          <ElFormItem label="所属平台" prop="platform">
            <PlatformQuery v-model="data.platform" placeholder="所属平台" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="销售方" prop="companyNo">
            <BusinessQuery v-model="data.companyNo" disabled />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="购买方" prop="khNo">
            <CustomerQuery v-model="data.khNo" placeholder="购买方" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="项目总预算" prop="budget_total">
            <div class="flex" style="width:100%">
              <ElInputNumber class="flex-1" v-model="data.budget_total" controls-position="right" :precision="2" />
              <p class="ml-[10px]">元</p>
            </div>
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="要求到货时间" prop="arrtime">
            <ElDatePicker :disabledDate="disabledDate" value-format="YYYY-MM-DD" v-model="data.arrtime"
              placeholder="要求到货时间" style="width:100%" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="8">
          <ElFormItem label="竞价截止时间" prop="endtime">
            <ElDatePicker :disabledDate="disabledDate" value-format="YYYY-MM-DD" v-model="data.endtime"
              placeholder="竞价截止时间" style="width:100%" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="项目用途" prop="use_desc">
            <ElInput type="textarea" v-model="data.use_desc" placeholder="项目用途" />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="商品要求" prop="ladder">
            <ElTable border size="small" :data="data.ladder">
              <ElTableColumn label="商品阶梯" width="70px">
                <template #="scope">{{ scope.$index + 1 }}</template>
              </ElTableColumn>

              <ElTableColumn label="商品类型" width="70px">
                <template #="scope">
                  <ElTag>
                    {{ goodTypeOptions.find(({ value }) => value === scope.row.good_type)?.label || '--' }}
                  </ElTag>
                </template>
              </ElTableColumn>

              <ElTableColumn label="预算单价" prop="budget_price" width="70px" />
              <ElTableColumn label="购买数量" prop="num" width="70px" />
              <ElTableColumn label="商品分类" min-width="180px">
                <template #="scope">{{ scope.row.can.length === 3 ? scope.row.can.map(({ name }) => name).join('/') : '' }}</template>
              </ElTableColumn>

              <ElTableColumn label="图片" width="70px">
                <template #="scope">
                  <ElImage v-if="scope.row.good_img" style="width:20px;height:20px" :src="scope.row.good_img"
                    previewTeleported :previewSrcList="[scope.row.good_img]" />
                </template>
              </ElTableColumn>

              <ElTableColumn label="商品名称" prop="good_name" min-width="180px" />
              <ElTableColumn label="操作" width="80px" v-if="type === 'create'">
                <template #header>
                  <div class="flex w-full justify-between">
                    <p>操作</p>
                    <ElTooltip content="添加商品要求" placement="top">
                      <ElButton link size="small" type="primary" :icon="useRenderIcon('add')"  @click="onAddLadder" />
                    </ElTooltip>
                  </div>
                </template>

                <template #="scope">
                  <el-button text type="primary" :icon="useRenderIcon('edits')" @click="() => onUpdateLadder(scope.$index)"  />
                </template>
              </ElTableColumn>
            </ElTable>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24" v-if="type === 'create'">
          <div class="flex justify-end">
            <ElButton type="primary" @click="submit">保存</ElButton>
          </div>
        </ElCol>
      </ElRow>
    </ElForm>


    <ladder-modal 
      v-model:visible="ladderTemp.visible"
      :index="ladderTemp.index"
      :detail="ladderTemp.detail" 
      :type="ladderTemp.type"  
      @add="handleLadderAdd"
      @update="handleLadderUpdate"
    />
  </div>
</template>
