<script setup lang="ts">
import {
  verifyFormColumns,
  ContractFormType,
  useTablePublic,
  columnsRecoveries,
  labelsRecoveries,
  columnsInvoice,
  labelsInvoice
} from '@/hooks/useTablePublic'
import {
  Storehouse_Contract_Get,
  Storehouse_VerifyContract_Add,
  Storehouse_VerifyContract_Edit,
  Storehouse_Contract_Gen_Number
} from '@/api/storehouse/index'
import { validate_float } from '@/views/salary/salary/relus'
import { ElMessage } from 'element-plus'
import TableDetail from './TableDetail.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 VerifyProject from './VerifyProject.vue'

const isNew = ref(true)
const isProduct = ref(false)
const tableData = ref<any[]>([])
let selectProductData: any[] = []
const formLabelWidth = ref('120px')
const ruleFormRef = ref<FormInstance>()
const contractNumberLoading = ref(false)
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 { resetForm, globalStore, validate_T_product } = useTablePublic()

const rules = reactive<FormRules>({
  T_number: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
  T_product: [{ validator: validate_T_product, trigger: 'blur' }],
  T_discount: [{ required: true, validator: validate_float(), trigger: 'blur' }],
  T_money: [{ required: true, validator: validate_float(), trigger: 'blur' }],
  T_date: [{ required: true, message: '请选择签订时间', trigger: 'blur' }],
  T_start_date: [{ required: true, message: '请选择起始时间', trigger: 'blur' }],
  T_end_date: [{ required: true, message: '请选择终止时间', trigger: 'blur' }],
  T_submit: [{ required: true, message: '请选择合同负责人', trigger: 'change' }]
})

const options = [
	{name: '先货后款', id: 'A'},
	{name: '收部分定金50%', id: 'B'},
	{name: '先款后货', id: 'C'}
]

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

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

const form:any = ref<ContractFormType>({
  T_uuid: '',
  T_number: '',
  T_task_id: '',
  T_product: '',
  T_money: '',
  T_discount: '',
  T_date: '',
  T_remark: '',
  T_project: '',
  T_pdf: '',
  T_submit: '',
  T_recoveries: '',
  T_invoice: '',
  T_submit_name: '',
  T_start_date: '',
  T_end_date: '',
  T_stamping_date: '',
  T_payment_method: '',
  T_type: '',
  T_uuid_name: '',
  T_remit: '',
  T_approval_money: '',
  T_approval_opinion: '',
  T_State: ''
})

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) => {
  form.value = { ...row }
  const res: any = await Storehouse_Contract_Get({
    User_tokey: globalStore.GET_User_tokey,
    T_number: row.T_number
  })
  if (res.Code === 200) {
    
    const { T_Product, T_invoice, T_recoveries, T_remark, T_submit_name, T_submit, T_start_date, T_end_date, T_stamping_date, T_payment_method } = res.Data
    form.value.T_remark = T_remark
    form.value.T_submit = T_submit_name
    form.value.T_uuid = T_submit
    form.value.T_start_date = T_start_date
    form.value.T_end_date = T_end_date
    form.value.T_stamping_date = T_stamping_date
    form.value.T_payment_method = T_payment_method
    T_Product &&
      (tableData.value = T_Product.map((item: any) => {
        item.Id = item.T_product_id
        item.T_img = item.T_product_img
        item.T_name = item.T_product_name
        item.T_class_name = item.T_product_class_name
        item.T_model = item.T_product_model
        item.T_spec = item.T_product_spec
        item.T_relation_sn = item.T_product_relation_sn
        item.count = item.T_product_total
        return item
      }))
    selectProductData = tableData.value
    T_invoice && InvoiceRef.value?.setMoneyDeatil(T_invoice)
    T_recoveries && RecoveriesRef.value?.setMoneyDeatil(T_recoveries)
    blurHandle()
  }
}

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

  // 设置产品的选中
  drawerProductRef.value?.selectTableChange(row)
}
const getMontageStr = (arr: any[], value1: string, value2: string ): string => {
  let str = ''
  arr.forEach(item => {
    str += `${item[value1]},${item[value2]}|`
  })
  return str
}
const getproductStr = (arr: any[], value1: string, value2: string ,value3: string): string => {
  let str = ''
  arr.forEach(item => {
    str += `${item[value1]},${item[value2]},${item[value3]}|`
  })
  return str
}
const getFomrParams = () => {
  const recoveriesData = RecoveriesRef.value?.getMoneyDeatil()
  const invoiceData = InvoiceRef.value?.getMoneyDeatil()
  if (recoveriesData?.length) form.value.T_recoveries = getMontageStr(recoveriesData, 'T_date', 'T_money')
  if (invoiceData?.length) form.value.T_invoice = getMontageStr(invoiceData, 'T_date', 'T_money')
  const product = getproductStr(tableData.value, 'Id', 'count','T_price')
  const params = {
    ...form.value,
    User_tokey: globalStore.GET_User_tokey,
    T_submit: form.value.T_uuid,
    T_product: product
  }
  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) {//true新增
        res = await Storehouse_VerifyContract_Add({ ...params, T_customer_id: props.verify_customer_id })
      } else {//false编辑
        res = await Storehouse_VerifyContract_Edit({ ...params, T_customer_id: props.verify_customer_id })
      }
      if (res.Code === 200) {
        ElMessage.success(`${isNew.value ? '添加' : '修改'}合同成功！！`)
        nextTick(() => {
          closeCancle()
          emit('onTableList')
        })
      }
    } else false
  })
}

const drawerProductRef = ref<InstanceType<typeof VerifyProject> | null>(null)
/**
 * 添加产品
 */
const AddProductionDetailed = () => {
  isProduct.value = true
  nextTick(() => {
    drawerProductRef.value?.openDrawer()
  })
}
/**
 * 产品选择 是否
 */
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)
  }
  getSummaries({ columns: verifyFormColumns, data: tableData.value })
}
/**
 * 全选
 */
const ProductSelectionAllChange = (selection: any[]) => (tableData.value = selection)
/**
 * 生成合同编号
 */
const getContractNumber = async () => {
  contractNumberLoading.value = true
  const res: any = await Storehouse_Contract_Gen_Number({ User_tokey: globalStore.GET_User_tokey }).catch(() => {
    contractNumberLoading.value = false
  })
  if (res.Code === 200) {
    contractNumberLoading.value = false
    form.value.T_number = res.Data
  }
}

const getSummaries = (param: any) => {
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (index === 1) {
      sums[index] = ''
      return
    }
    const values = data.map((item: any) => Number(item[column.property]))
    if (!values.every((value: any) => Number.isNaN(value))) {
      sums[index] = values.reduce((prev: any, curr: any) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      if (index === 8) {
        form.value.T_money = sums[index]
      }
    } else {
      sums[index] = ''
    }
  })

  return sums
}

/**
 * 合同负责人
 */
const selectApprover = () => receiveUserdialog.value?.openDrawer()
const getReceiveInfo = ({ T_uuid, T_name }: { T_uuid: string; T_name: string }) => {
  form.value.T_submit = T_name
  form.value.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 props = defineProps<{ verify_customer_id: string }>()



defineExpose({
  openDrawer
})

</script>

<template>
  <div class="verify-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-input v-model="form.T_number" placeholder="请输入合同编号" class="w-50" />
            <el-button :loading="contractNumberLoading" :disabled="!isNew" type="primary" @click="getContractNumber"
              >生成合同编号</el-button
            >
            <el-button type="primary" @click="AddProductionDetailed">
              <el-icon><CirclePlusFilled /></el-icon><span style="margin-left: 6px">验证</span>
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="验证明细：" :label-width="formLabelWidth" prop="T_product">
          <el-table
            border
            show-summary
            :summary-method="getSummaries"
            :data="tableData"
            style="width: 100%"
            :header-cell-style="{ height: '50px' }"
          >
            <template v-for="item in verifyFormColumns" :key="item.prop">
              <el-table-column show-overflow-tooltip v-bind="item" v-if="item.fixed !== 'right'">
                <template #header v-if="item.prop === 'count'">
                  <span style="color: red">*数量</span>
                </template>
                <template #default="{ row }" v-if="item.prop === item.name">
                  <el-input
                    v-if="item.prop === 'count'"
                    v-model.number="row.count"
                    type="text"
                    autocomplete="off"
                    @blur="blurHandle"
                  />
                  <el-input
                    v-if="item.prop === 'T_price'"
                    v-model.number="row.T_price"
                    type="text"
                    autocomplete="off"
                    @blur="blurHandle"
                  />
                  <ImageCom v-if="item.prop === 'T_img'" :src="row.T_img" />
                </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>
          </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_discount">
          <el-input
            v-model="form.T_discount"
            type="text"
            autocomplete="off"
            placeholder="请输入合同金额"
            class="w-50"
          />
        </el-form-item>
        <el-form-item label="签订时间：" :label-width="formLabelWidth" prop="T_date">
          <el-date-picker
            class="my-date-picker"
            style="width: 21.5rem"
            v-model="form.T_date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="起始时间：" :label-width="formLabelWidth" prop="T_start_date">
          <el-date-picker
            class="my-date-picker"
            style="width: 21.5rem"
            v-model="form.T_start_date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="终止时间：" :label-width="formLabelWidth" prop="T_end_date">
          <el-date-picker
            class="my-date-picker"
            style="width: 21.5rem"
            v-model="form.T_end_date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
		  <el-form-item label="盖章时间：" :label-width="formLabelWidth" prop="T_stamping_date">
			  <el-date-picker
				  class="my-date-picker"
				  style="width: 21.5rem"
				  v-model="form.T_stamping_date"
				  type="date"
				  placeholder="选择日期"
				  format="YYYY-MM-DD"
				  value-format="YYYY-MM-DD"
			  />
		  </el-form-item>
		  <el-form-item label="付款方式：" class="m-b-6" :label-width="formLabelWidth" prop="T_payment_method">
			  <el-select v-model="form.T_payment_method" class="w-50 m-2" clearable placeholder="请选择付款方式~">
				  <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"/>
			  </el-select>
		  </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-item label="项目：" :label-width="formLabelWidth" prop="T_project">
          <el-input v-model="form.T_project" placeholder="请输入项目名称" class="w-50" />
        </el-form-item>
        <el-form-item label="合同备注：" :label-width="formLabelWidth" prop="T_remark">
          <el-input
            class="w-50"
            v-model="form.T_remark"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item label="上传附件：" :label-width="formLabelWidth" prop="T_pdf">
          <Upload
            v-model="form.T_pdf"
            class="w-50"
            ref="uploadRef"
            :limit="1"
            successText="文件上传成功！！"
            errorText="文件上传失败"
            accept=".pdf"
            listType="text"
          >
            <el-button type="primary">上传文件</el-button>
            <template #tip> 只能上传pdf格式文件!!</template>
          </Upload>
        </el-form-item>
        <el-form-item label="回款明细：" :label-width="formLabelWidth" prop="T_recoveries">
          <TableDetail ref="RecoveriesRef" :columns="columnsRecoveries" title="回款明细" :labels="labelsRecoveries">
            <template #add="{ AddDetail }">
              <el-button type="primary" @click="AddDetail">
                <el-icon><Plus /></el-icon><span style="margin-left: 6px">添加</span>
              </el-button>
            </template>
          </TableDetail>
        </el-form-item>
        <el-form-item label="开票明细：" :label-width="formLabelWidth" prop="T_invoice">
          <TableDetail ref="InvoiceRef" :columns="columnsInvoice" 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>
          </TableDetail>
        </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="合同负责人" />
    <VerifyProject
      v-if="isProduct"
      ref="drawerProductRef"
      :selectProductData="selectProductData"
      @ontableData="ProductselectionChange"
      @ontableDataAll="ProductSelectionAllChange"
    ></VerifyProject>
  </div>
</template>

<style scoped lang="scss">
.verify-form {
  .btn {
    margin-top: 32px;
    display: flex;
    justify-content: center;
    .el-button {
      padding: 0 32px;
    }
  }
  .w-50 {
    width: 21.5rem;
  }
}
</style>
