<script setup lang="ts">
import {
  columns,
  royalty,
  ContractFormType,
  useTablePublic,
  columnsRemit,
  labelsInvoice,
  useStapublicFun
} from '@/hooks/useTablePublic'

import {
  Storehouse_Contract_Gen_Number
} from '@/api/storehouse/index'

import { percentage_Get,percentage_Remit} from '@/api/percentage/index'

import { ElMessage } from 'element-plus'
import PercentageTable from './PercentageTable.vue'
import { ref, reactive, nextTick } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import { Delete } from '@element-plus/icons-vue'
import Upload from '@/components/Upload/index.vue'
import ImageCom from '@/components/Image/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import ContractUser from '@/views/storehouse/outStock/receiveUser.vue'
import InStorageProduct from '@/views/storehouse/inventory/InStorageProduct.vue'
import { json } from 'stream/consumers'

const isNew = ref(true)
const isProduct = ref(false)
const tableData = ref<any[]>([])
const tableDatalty = 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 PercentageTable> | null>(null)
const InvoiceRef = ref<InstanceType<typeof PercentageTable> | null>(null)

const rules = reactive<FormRules>({
	T_state: [{ required: true, message: '请选择审批结果', trigger: 'blur' }],
	T_approval_money: [{ required: true, message: '请输入审批金额', trigger: 'change' }],
	T_approval_opinion: [{ required: true, message: '请输入审批意见', trigger: 'blur' }]
})

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

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

const form = reactive<ContractFormType>({
  T_uuid: '',
  T_type: '',
  T_task_id: '',
  T_number: '',
  T_customer: '',
  T_product: '',
  T_money: '',
  T_uuid_name:'',
  T_discount: '',
  T_date: '',
  T_remark: '',
  T_pdf: '',
  T_submit: '',
  T_recoveries: '',
  T_remit: '',
  T_invoice:'',
  T_submit_name: '',
  T_approval_money: '',
  T_approval_opinion: '',
  T_State: null
})

const openDrawer = (type: string, row?: any) => {
  isNew.value = type === 'new' ? 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_submit
  form.T_pdf = row.T_pdf
  form.T_date = row.T_date
  form.T_money = row.T_money
  form.T_discount = row.T_discount
  form.T_uuid_name = row.T_uuid_name

  form.T_submit = row.T_submit_name
  form.T_number = row.T_number
  form.T_customer = row.T_customer

  form.T_approval_money = row.T_approval_money
  form.T_approval_opinion = row.T_approval_opinion
  form.T_State = row.T_State

  const res: any = await percentage_Get({
    User_tokey,
    T_id: row.Id
  })
  if (res.Code === 200) {
    console.log('打款明细',res)
    const { T_remit, T_recoveries, T_remark,T_item } = res.Data
    form.T_remark = T_remark
    tableDatalty.value = T_item
    selectProductData = tableData.value
    T_remit && InvoiceRef.value?.setMoneyDeatil(T_remit)
    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 getMontageStr = (arr: any[], value1: string, value2: string): string => {
  let str = ''
  arr.forEach(item => {
    str += `${item[value1]},${item[value2]}|`
  })
  return str
}

const getFomrParams = () => {
  const recoveriesData = RecoveriesRef.value?.getMoneyDeatil()
  const invoiceData = InvoiceRef.value?.getMoneyDeatil()
  if (recoveriesData?.length) form.T_recoveries = getMontageStr(recoveriesData, 'T_date', 'T_money')
  if (invoiceData?.length) form.T_remit = getMontageStr(invoiceData, 'T_date', 'T_money')
  const product = getMontageStr(tableData.value, 'Id', 'count')
  const params = {
    ...form,
    User_tokey,
    T_submit: form.T_uuid,
    T_product: product
  }
  return params
}

const props = defineProps({
  ContForm: {
    type: Object,
    default: () => {},
  },
})
const AddContract = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let arr:any = InvoiceRef.value?.getMoneyDeatil()
      let mapArr:any = []
      arr?.forEach((item:any)=>{mapArr.push( item.T_date + ',' + item.T_money)})
      const reslut:any = await percentage_Remit({
        T_id:props.ContForm.id,
        T_remit:mapArr.join('|')
      })
      console.log('添加123456',reslut)
      if (reslut.Code === 200) {
        ElMessage.success(`打款明细调整成功！！`)
        nextTick(() => {
          closeCancle()
          emit('onTableList')
        })
      }
    } else false
  })
}

const drawerProductRef = ref<InstanceType<typeof InStorageProduct> | null>(null)

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()
}
defineExpose({
  openDrawer
})
</script>

<template>
  <div class="contract-form">
    <Drawer ref="drawerRef" :handleClose="callbackDrawer" size="80%">
      <template #header="{ params }">
        <h4 :id="params.titleId" :class="params.titleClass">打款明细</h4>
      </template>
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item label="任务编号：" :label-width="formLabelWidth" prop="T_task_id">
            <el-input v-model="form.T_task_id" :disabled="!isNew" placeholder="请输入任务编号" class="w-50" />
        </el-form-item>
        <el-form-item label="提成类型：" :label-width="formLabelWidth" prop="T_type">
          {{ form.T_type == 1 ? '验证实施' : '报告编写' }}
        </el-form-item>
        <el-form-item label="提成明细：" :label-width="formLabelWidth" prop="T_product">
          <el-table border stripe :data="tableDatalty" style="width: 100%"
            :header-cell-style="{ background: '#dedfe0', height: '50px' }">
            <template v-for="item in royalty" :key="item.prop">
              <el-table-column show-overflow-tooltip v-bind="item">
                <template #default="{ row }" v-if="item.prop === item.name">
                  <div v-if="item.prop === 'T_priceNum'">{{Number(row.T_num) * Number(row.T_price)}}</div>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </el-form-item>
        <el-form-item label="提成金额：" :label-width="formLabelWidth" prop="T_money">
          {{ form.T_money}}
        </el-form-item>
        <el-form-item label="提成人员：" :label-width="formLabelWidth" prop="T_uuid_name">
          {{ form.T_uuid_name}}
        </el-form-item>
        <el-form-item label="审批金额：" :label-width="formLabelWidth" prop="T_approval_money">
          {{ form.T_approval_money}}
        </el-form-item>
        <el-form-item label="审批意见：" :label-width="formLabelWidth" prop="T_approval_opinion">
          {{ form.T_approval_opinion}}
        </el-form-item>
        <el-form-item label="状态：" :label-width="formLabelWidth" prop="T_State">
          {{ useStapublicFun(form?.T_State) }}
        </el-form-item>
        <el-form-item label="打款明细：" :label-width="formLabelWidth" prop="T_remit">
          <PercentageTable ref="InvoiceRef" :columns="columnsRemit" :showTable="props.ContForm.showTable?true:false" title="打款明细" :labels="labelsInvoice">
            <template #add="{ AddDetail }">
              <el-button type="primary" @click="AddDetail">
                <el-icon>
                  <Plus />
                </el-icon><span style="margin-left: 6px">添加</span>
              </el-button>
            </template>
          </PercentageTable>
        </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>
  </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>
