<script setup lang="ts">
import {
  Mycolumns,
  MyPercentageFormType,
  useTablePublic,
} from '@/hooks/useTablePublic'
import {
  percentage_Get,
  percentage_Edit,
  percentage_Add,
  VerifyContract_List
} from '@/api/mypercentage/index'


import { ElMessage } from 'element-plus'
import TableDetail from './TableDetail.vue'
import { ref, reactive, nextTick,onMounted } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import { Delete } from '@element-plus/icons-vue'
import Upload from '@/components/Upload/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import ContractUser from '@/views/storehouse/outStock/receiveUser.vue'
import MyPercentageFormStorage from '@/views/storehouse/inventory/MyPercentageFormStorage.vue'

const isNew = ref(true)
const isProduct = ref(false)
const tableData = ref<any[]>([])
let selectProductData: any[] = []
const formLabelWidth = ref('120px')
const { resetForm, globalStore, validate_T_product } = useTablePublic()
const ruleFormRef = ref<FormInstance>()
const contractNumberLoading = ref(false)
const User_tokey = globalStore.GET_User_tokey
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const uploadRef = ref<InstanceType<typeof Upload> | null>(null)
const receiveUserdialog = ref<InstanceType<typeof ContractUser> | null>(null)
const RecoveriesRef = ref<InstanceType<typeof TableDetail> | null>(null)
const InvoiceRef = ref<InstanceType<typeof TableDetail> | null>(null)

const rules = reactive<FormRules>({
  T_number: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
  T_customer: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  T_type: [{ required: true, message: '请选择合同类型', trigger: 'blur' }],
  T_product: [{ validator: validate_T_product, message: '必填项', trigger: 'blur' }],
  T_money: [{ required: true, message: '请输入合同金额', trigger: 'blur' }],
  T_discount: [{ required: true, message: '请输入优惠金额', trigger: 'blur' }],

  T_date: [{ required: true, message: '请选择签订时间', trigger: 'blur' }],
  T_submit: [{ required: true, message: '请选择合同负责人', trigger: 'change' }],
  T_submit_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }]
})

const callbackDrawer = (done: () => void) => {
  closeCancle()
  done()
}

// 父级方法
const emit = defineEmits<{ (event: 'onTableList'): void }>()

const form = reactive<MyPercentageFormType>({
  T_id: '',
  T_uuid: '',
  T_submit: '',
  T_type: 1,
  T_number: '',
  T_money: '',
  T_item: '',
  T_product:null
})

const openDrawer = (type: string, row?: any) => {
  console.log('传值', type, row)
  if(row){form.T_id = row.Id}
  isNew.value = type === 'new' ? true : false //true新增申请   false编辑
  if (!isNew.value) {//编辑调接口渲染
    nextTick(() => {
      editDataEcho(row)
    })
  }
  drawerRef.value?.openDrawer()
}

// edit data echo
const editDataEcho = async (row: any) => {
  console.log('编辑赋值', row)
  form.T_uuid = row.T_uuid
  form.T_type = row.T_type
  form.T_number = row.T_number
  form.T_money = row.T_money
  form.T_number = row.T_number
  form.T_submit = row.T_uuid_name

  const res: any = await percentage_Get({ User_tokey, T_id: row.Id })
  console.log('请求返回', res)
  if (res.Code === 200) {
    const { T_Product, T_invoice, T_recoveries, T_item } = res.Data
    T_item && (tableData.value = T_item.map((item: any) => {
      item.count = item.T_num
      return item
    }))
    selectProductData = tableData.value
    T_invoice && InvoiceRef.value?.setMoneyDeatil(T_invoice)
    T_recoveries && RecoveriesRef.value?.setMoneyDeatil(T_recoveries)
    blurHandle()
  }
}

const blurHandle = () => {
  form.T_product = tableData.value.map(item => {
    if (!item.count) return undefined
    return `${item.Id},${item.count}|`
  })
}
const deleteProduct = (row: any) => {
  tableData.value = tableData.value.filter(item => item.Id !== row.Id)

  // 设置产品的选中
  drawerProductRef.value?.selectTableChange(row)
}

const getFomrParams = () => {
  const params = {...form}
  params.T_item = params?.T_product.join('')
  delete params.T_product
  delete params.T_submit
  return params
}

const AddContract = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      const params = getFomrParams()
      if (isNew.value) {
        res = await percentage_Add(params)
      } else {
        res = await percentage_Edit(params)
      }
      if (res.Code === 200) {
        ElMessage.success(`${isNew.value ? '添加' : '修改'}成功！！`)
        nextTick(() => {
          closeCancle()
          emit('onTableList')
        })
      }
    } else false
  })
}

const drawerProductRef = ref<InstanceType<typeof MyPercentageFormStorage> | null>(null)
/**
 * 添加产品
 */
const AddProductionDetailed = () => {
  // selectTable.value.toggleRowSelection(tableProductData.value.find(item => {return 1 == item.Id;}), true )


  //有问题
  isProduct.value = true
  nextTick(() => {
    drawerProductRef!.value!.initParam!.T_type = form.T_type || undefined
    drawerProductRef.value?.searchModelHandle()
    drawerProductRef.value?.openDrawer()
    console.log('添加',tableData.value,drawerProductRef.value)
    if(drawerProductRef.value){
      drawerProductRef.value.toggleSelectionFun(tableData.value)
    }
  })
}

interface User {
  T_id: number
  T_name: string
  T_num: number
  count: number
}


/**
 * 产品选择 是否
 */
const ProductselectionChange = (row: any) => {
  const index = tableData.value.findIndex((item: any) => item.Id === row.Id)
  if (index === -1) {
    row.count = ''
    tableData.value.push(row)
  } else {
    tableData.value.splice(index, 1)
  }
}
/**
 * 全选
 */
const ProductSelectionAllChange = (selection: any[]) => (tableData.value = selection)
/**
 * 生成合同编号
 */
const getContractNumber = async () => {
  contractNumberLoading.value = true
}
/**
 * 合同负责人
 */
const selectApprover = () => receiveUserdialog.value?.openDrawer()
const getReceiveInfo = ({ T_uuid, T_name }: { T_uuid: string; T_name: string }) => {
  console.log('123', T_uuid, T_name)
  form.T_submit = T_name
  form.T_uuid = T_uuid
}
const closeCancle = () => {
  resetForm(ruleFormRef.value)
  isNew.value = isProduct.value = false
  tableData.value = []
  selectProductData = []
  drawerProductRef.value?.clearSelection()
  RecoveriesRef.value?.clearDetail()
  InvoiceRef.value?.clearDetail()
  drawerRef.value?.closeDrawer()
}

const loading = ref(false)
interface ListItem {
    value: string
    label: string
}
const list = ref<ListItem[]>([])
const options = ref<ListItem[]>([])
const click2 = async ()=>{options.value = list.value }
//函数
const VerifyltemApi = async ()=>{
  const result:any = await VerifyContract_List({})
  console.log('返回',result)
  let arr = result.Data.Data || []
  list.value = arr.map((item:any) => {
      return { value: item.T_number, label: item.T_number}
  })
}
const remoteMethod = async(query: string) => {
    if (query) {
        loading.value = true
        setTimeout(() => {
            loading.value = false
            options.value =  list.value.filter((item:any) => {
                return item.label.toLowerCase().includes(query.toLowerCase())
            })
        }, 200)
    } else {
        options.value = []
    }
}
defineExpose({
  openDrawer,
  VerifyltemApi
})
</script>

<template>
  <div class="contract-form">
    <Drawer ref="drawerRef" :handleClose="callbackDrawer" size="80%">
      <template #header="{ params }">
        <h4 :id="params.titleId" :class="params.titleClass">{{ isNew ? '申请' : '编辑' }} - 提成</h4>
      </template>
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item label="合同编号：" :label-width="formLabelWidth" prop="T_number">
          <div>
            <el-select v-model="form.T_number" class="w-50" filterable remote reserve-keyword placeholder="请输入合同编号"
                :remote-method="remoteMethod" :loading="loading" @click="click2" clearable style="width: 200px;">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button :loading="contractNumberLoading" type="primary" @click="getContractNumber" style="margin-left: 10px;">查看合同详情</el-button>
          </div>
        </el-form-item>
        <el-form-item label="提成类型：" :label-width="formLabelWidth" prop="T_type">
          <el-radio-group v-model="form.T_type">
            <el-radio :label="1">实施提成</el-radio>
            <el-radio :label="2">报告提成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="验证产品明细：" :label-width="formLabelWidth" prop="T_product">
          <el-table border stripe :data="tableData" style="width: 100%"
            :header-cell-style="{ background: '#dedfe0', height: '50px' }">
            <template v-for="item in Mycolumns" :key="item.prop">
              <el-table-column v-bind="item" v-if="item.fixed !== 'right'">
                <template #header v-if="item.prop === 'T_num'">
                  <span style="color: red">*数量</span>
                </template>
                <template #default="{ row }" v-if="item.prop === item.name">
                  <el-input v-if="item.prop === 'T_num'" v-model.number="row.count" type="text" autocomplete="off"
                    @blur="blurHandle" />
                  <div v-if="item.prop === 'T_priceNum'">{{ Number(row.count) * Number(row.T_price) }}</div>
                </template>
              </el-table-column>
              <el-table-column v-bind="item" v-if="item.fixed === 'right'">
                <template #default="{ row }">
                  <el-button link type="danger" size="small" :icon="Delete" @click="deleteProduct(row)">删除</el-button>
                </template>
              </el-table-column>
            </template>
            <template #append>
              <el-button type="primary" @click="AddProductionDetailed">
                <el-icon>
                  <Plus />
                </el-icon><span style="margin-left: 6px">添加验证</span>
              </el-button>
            </template>
          </el-table>
        </el-form-item>

        <el-form-item label="合同金额：" :label-width="formLabelWidth" prop="T_money">
          <el-input v-model="form.T_money" type="text" autocomplete="off" placeholder="请输入合同金额" class="w-50" />
        </el-form-item>
        <el-form-item label="合同负责人：" :label-width="formLabelWidth" prop="T_submit">
          <el-input v-model="form.T_submit" placeholder="请选择合同负责人" class="w-50" @focus="selectApprover" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-divider border-style="dashed" />
          <div class="btn">
            <el-button @click="closeCancle">取消</el-button>
            <el-button v-if="isNew" color="#626aef" @click="AddContract(ruleFormRef)">提交</el-button>
            <el-button v-else color="#626aef" @click="AddContract(ruleFormRef)">修改</el-button>
          </div>
        </div>
      </template>
    </Drawer>
    <ContractUser ref="receiveUserdialog" @onUserInfo="getReceiveInfo" title="合同负责人" />
    <MyPercentageFormStorage v-if="isProduct" ref="drawerProductRef" :selectProductData="selectProductData"
      @ontableData="ProductselectionChange" @ontableDataAll="ProductSelectionAllChange"></MyPercentageFormStorage>
  </div>
</template>

<style scoped lang="scss">
.contract-form {
  :deep(.el-table--border .el-table__cell) {
    border-right: 0;
  }

  :deep(.table-header),
  :deep(.card) {
    border: 0;
  }

  .box-card {
    height: 100%;

    :deep(.el-card__body) {
      height: calc(100% - 70px);
    }
  }

  .btn {
    margin-top: 32px;
    display: flex;
    justify-content: center;

    .el-button {
      padding: 0 32px;
    }
  }

  .w-50 {
    width: 21.5rem;
  }
}
</style>
