<script setup lang="ts">
import {
  columns,
  ContractFormType,
  useTablePublic,
  columnsRecoveries,
  labelsRecoveries,
  columnsInvoice,
  labelsInvoice
} from '@/hooks/useTablePublic'
import {
  Storehouse_Contract_Get,
  Storehouse_Contract_Add,
  Storehouse_Contract_Edit,
  Storehouse_Contract_Gen_Number
} from '@/api/storehouse/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 { 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'

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, 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<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_invoice: '',
  T_remit: '',
  T_submit_name: '',
  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.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_submit = row.T_submit_name
  form.T_number = row.T_number
  form.T_customer = row.T_customer

  const res: any = await Storehouse_Contract_Get({
    User_tokey,
    T_number: row.T_number
  })
  if (res.Code === 200) {
    const { T_Product, T_invoice, T_recoveries, T_remark } = res.Data
    form.T_remark = T_remark
    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.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 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_invoice = 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 AddContract = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      const params = getFomrParams()
      if (isNew.value) {
        res = await Storehouse_Contract_Add(params)
      } else {
        res = await Storehouse_Contract_Edit(params)
      }
      if (res.Code === 200) {
        ElMessage.success(`${isNew.value ? '添加' : '修改'}合同成功！！`)
        nextTick(() => {
          closeCancle()
          emit('onTableList')
        })
      }
    } else false
  })
}

const drawerProductRef = ref<InstanceType<typeof InStorageProduct> | 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)
  }
}
/**
 * 全选
 */
const ProductSelectionAllChange = (selection: any[]) => (tableData.value = selection)
/**
 * 生成合同编号
 */
const getContractNumber = async () => {
  contractNumberLoading.value = true
  const res: any = await Storehouse_Contract_Gen_Number({ User_tokey }).catch(() => {
    contractNumberLoading.value = false
  })
  if (res.Code === 200) {
    contractNumberLoading.value = false
    form.T_number = res.Data
  }
}
/**
 * 合同负责人
 */
const selectApprover = () => receiveUserdialog.value?.openDrawer()
const getReceiveInfo = ({ T_uuid, T_name }: { T_uuid: string; T_name: string }) => {
  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()
}
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">{{ 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" :disabled="!isNew" placeholder="请输入合同编号" class="w-50" />
            <el-button :loading="contractNumberLoading" :disabled="!isNew" type="primary" @click="getContractNumber"
              >生成合同编号</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="客户名称：" :label-width="formLabelWidth" prop="T_customer">
          <el-input v-model="form.T_customer" placeholder="请输入客户名称" class="w-50"/>
        </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 columns" :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"
                  />
                  <span v-if="item.prop === 'T_relation_sn'">
                    <el-tag v-if="row.T_relation_sn === 1" effect="dark">是</el-tag>
                    <el-tag v-else type="success" effect="dark">否</el-tag>
                  </span>
                  <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>
            <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_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_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_submit_name">
          <el-input v-model="form.T_submit_name" 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="合同负责人" />
    <InStorageProduct
      v-if="isProduct"
      ref="drawerProductRef"
      :selectProductData="selectProductData"
      @ontableData="ProductselectionChange"
      @ontableDataAll="ProductSelectionAllChange"
    ></InStorageProduct>
  </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>
