<script setup lang="ts">
import {
  Mycolumns,
  MyPercentageFormTypeFrom,
  useTablePublic,
} from '@/hooks/useTablePublic'
import {
  percentage_Get,
  percentage_Edit,
  percentage_Approval,
  percentage_Add,
} from '@/api/mypercentage/index'
import { useRouter, useRoute } from 'vue-router'

import { ElMessage } from 'element-plus'
import TableDetail from './TableDetail.vue'
import { ref, reactive, nextTick,watch } 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/MyPercentageFormStorage1.vue'
import verifyxiang from '@/views/storehouse/sales/verifyxiang.vue'

const isNew = ref(true)
const isProduct = ref(false)
const tableData = ref<any[]>([])
const formLabelWidth = ref('120px')
const { resetForm, globalStore } = useTablePublic()
const ruleFormRef = ref<FormInstance>()
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_state: [{ required: true, message: '请选择审批结果', trigger: 'blur' }],
  T_approval_money: [{ required: true, message: '请输入审批金额', trigger: 'change' }],
})

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

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

const form = reactive<MyPercentageFormTypeFrom>({
  T_id: '',
  T_uuid: '',
  T_submit: '',
  T_type: 1,
  // T_number: '',
  T_money: '',
  // T_item: '',
  T_product:null,
  T_state:'',
  T_approval_money:'',
  T_approval_opinion:'',
  T_uuid_name:'',
  T_task_id:'',
  T_device_type:'',
  T_verify_type: '',
  T_verifyCompany: 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_money = row.T_money
  form.T_task_id = row.T_task_id
  form.T_uuid_name = row.T_uuid_name
  form.T_device_type = row.T_device_type
  form.T_verify_type = row.T_verify_type
  form.T_verifyCompany = row.T_verifyCompany

  form.T_state = 2
  form.T_approval_money = row.T_approval_money
  form.T_approval_opinion = row.T_approval_opinion

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

    T_invoice && InvoiceRef.value?.setMoneyDeatil(T_invoice)
    T_recoveries && RecoveriesRef.value?.setMoneyDeatil(T_recoveries)
  }
}

const getFomrParams = () => {
  const params = {...form}
  return params
}

const AddContract = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      await blurfindFun()
      const params = getFomrParams()
      if (isNew.value) {
        res = await percentage_Add(params)
      } else {
        res = await percentage_Approval(params)
      }
      if (res.Code === 200) {
        ElMessage.success(`${isNew.value ? '添加' : '修改'}成功！！`)
        nextTick(() => {
          closeCancle()
          emit('onTableList')
        })
      }
    } else false
  })
}
//筛选验证产品明细是否填写了数量
const blurfindFun = async ()=>{
  return new Promise((reslove:any)=>{
    const reslut = tableData.value.every((item:any)=>item.count!='')
    if(!reslut){
      ElMessage.error('请填写验证产品明细【数量】')
    }else{
      reslove()
    }
  })
}
const drawerProductRef = ref<InstanceType<typeof MyPercentageFormStorage> | null>(null)

const closeCancle = () => {
  resetForm(ruleFormRef.value)
  isNew.value = isProduct.value = false
  tableData.value = []
  drawerProductRef.value?.clearSelection()
  RecoveriesRef.value?.clearDetail()
  InvoiceRef.value?.clearDetail()
  drawerRef.value?.closeDrawer()
}

watch(() => tableData.value, (newvalue:any) => {
  form.T_money = newvalue.reduce((sum:any, e:any) => sum + Number(e.T_price* e.count || 0), 0)
},{ deep: true,immediate:true});


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_verifyCompany">-->
<!--			{{form.T_verifyCompany.T_name}}-->
<!--        </el-form-item>-->
        <el-form-item label="任务编号：" :label-width="formLabelWidth" prop="T_task_id">
			{{form.T_task_id}}
        </el-form-item>
        <el-form-item label="提成类型：" :label-width="formLabelWidth" prop="T_type">
           {{ form.T_type==1?'实施提成':'报告提成' }}
<!--          <el-radio-group v-model="form.T_type" :disabled="true">-->
<!--            <el-radio :label="1" v-if="form.T_type==1">实施提成</el-radio>-->
<!--            <el-radio :label="2" v-if="form.T_type==2">报告提成</el-radio>-->
<!--          </el-radio-group>-->
        </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_state">
          <el-radio-group v-model="form.T_state">
            <el-radio :label="2">已通过</el-radio>
            <el-radio :label="3">未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批金额：" :label-width="formLabelWidth" prop="T_approval_money">
          <el-input v-model="form.T_approval_money" placeholder="请输入审批金额" class="w-50"/>
        </el-form-item>
        <el-form-item label="审批意见：" :label-width="formLabelWidth" prop="T_approval_opinion">
          <el-input
            class="w-50"
            v-model="form.T_approval_opinion"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            placeholder=""
          />
        </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>
