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


import { ElMessage } from 'element-plus'
import TableDetail from './TableDetail.vue'
import { ref, reactive, nextTick } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import SelectVerifyCompany from '@/views/storehouse/sales/SelectVerifyCompany.vue'
const isNew = ref(true)
const isProduct = ref(false)
const tableData = ref<any[]>([])
const formLabelWidth = ref('120px')
const { resetForm } = useTablePublic()
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)

const RecoveriesRef = ref<InstanceType<typeof TableDetail> | null>(null)
const InvoiceRef = ref<InstanceType<typeof TableDetail> | null>(null)
const verifyCompany = ref<InstanceType<typeof SelectVerifyCompany> | null>(null)


const rules = reactive<FormRules>({
  T_company_uuid: [{ required: true, message: '请输入公司', trigger: 'blur' }],
  T_type: [{ required: true, message: '请选择提成类型', trigger: 'blur' }],
  T_device_type: [{ required: true, message: '请选择设备类型', trigger: 'blur' }],
  T_verify_type: [{ required: true, message: '请选择眼增类型', trigger: 'blur' }],
})

const data: any = reactive({
	deviceType: [{T_name:'其他'}]
})

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

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

const form = reactive<MyPercentageFormType>({
  T_id: '',
  T_device_type: '',
  T_verify_type: '',
  T_company_uuid: '',
  T_verifyCompany_name: '',
  T_money: '',
  T_type: 1,

})

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_type = row.T_type
  form.T_device_type = row.T_device_type
  form.T_verify_type = row.T_verify_type
  form.T_company_uuid = row.T_company_uuid
  form.T_verifyCompany_name = row.T_verifyCompany.T_name
  form.T_money = row.T_money
}

const getFomrParams = () => {
  const params = {...form}
  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 closeCancle = () => {
  resetForm(ruleFormRef.value)
  isNew.value = isProduct.value = false
  tableData.value = []
  RecoveriesRef.value?.clearDetail()
  InvoiceRef.value?.clearDetail()
  drawerRef.value?.closeDrawer()
}

defineExpose({
  openDrawer,
})
const selectCompany = () => verifyCompany.value?.openDrawer()
const getCompanyInfo = ({T_uuid, T_name}: { T_uuid: string; T_name: string }) => {
	form.T_verifyCompany_name = T_name
	form.T_company_uuid = T_uuid
}

</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_verifyCompany_name">
			<el-input v-model="form.T_verifyCompany_name" type="text" autocomplete="off" placeholder="请选择公司"
					  @focus="selectCompany" class="w-50" />
        </el-form-item>
        <el-form-item label="提成类型：" :label-width="formLabelWidth" prop="T_type">
          <el-radio-group v-model="form.T_type" :disabled="isNew?false:true" >
            <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_device_type">
          <el-select v-model="form.T_device_type" class="w-50" placeholder="请选择设备类型">
            <el-option v-for="item in data.deviceType" :key="item.T_name" :label="item.T_name" :value="item.T_name" />
          </el-select>
        </el-form-item>
		  <el-form-item label="验证类型：" :label-width="formLabelWidth" prop="T_verify_type">
			  <el-input v-model="form.T_verify_type" placeholder="请输入验证类型" class="w-50" />
		  </el-form-item>
		  <el-form-item label="提成金额：" :label-width="formLabelWidth" prop="T_money">
			  <el-input v-model="form.T_money" placeholder="请输入提成金额" class="w-50" />
		  </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>

    <SelectVerifyCompany ref="verifyCompany" @onUserInfo="getCompanyInfo" title="公司列表" />
  </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>
