<script setup lang="ts">
import { ref, reactive, nextTick, computed } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ColumnProps } from '@/components/TableBase/interface/index'
import { generateRandom } from '@/utils/common'

const isNew = ref(true)
const tableData = ref<any[]>([])
const formLabelWidth = ref('140px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)

const form = ref({
  	id: '',
	T_name:'',
	T_model:'',
	T_spec:'',
	T_quantity:'',
	T_demand:'',
	T_remark:'',
	T_state:1,
	T_date:'',
	T_unit_price:'',
	T_amount:'',
	T_reference_site:'',
})
const rules = reactive<FormRules>({
	T_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
	T_quantity: [{ required: true, message: '数量', trigger: 'blur' }]
})
const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80, align: 'center' },
  { prop: 'T_name', label: '名称', align: 'center' },
  { prop: 'T_model', label: '型号', align: 'center', width: 100 },
  { prop: 'T_spec', label: '规格', align: 'center', width: 100 },
  { prop: 'T_quantity', label: '数量', align: 'center'},
  { prop: 'T_reference_site', label: '参考网址', align: 'center', width: 140 },
  { prop: 'T_demand', label: '需求', align: 'center', width: 140 },
  { prop: 'T_remark', label: '备注', align: 'center', width: 140 },
  { prop: 'T_state', label: '状态', align: 'center', width: 80 },
  { prop: 'T_date', label: '采购时间', align: 'center', width: 120 },
  { prop: 'T_unit_price', label: '采购单价', align: 'center', width: 100},
  { prop: 'T_amount', label: '采购金额', align: 'center', width: 100},
  { prop: 'operation', label: '操作', width: 160, fixed: 'right', align: 'center' }
]

const openProductionDetailed = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  if (!isNew.value) {
    form.value = { ...row }
  }
  drawerRef.value?.openDrawer()
}
const callbackDrawer = (done: () => void) => {
  done()
  resetForm(ruleFormRef.value)
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const deletePurchaseDetail = (id: string) => {
  tableData.value = tableData.value.filter((item: any) => item.id !== id)
  emit('onPlanning', tableData.value)
}
const addPurchaseDetail = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      if (isNew.value) {
        tableData.value.push({ ...form.value, id: generateRandom() })
      } else {
        const index = tableData.value.findIndex(item => item.id === form.value.id)
        tableData.value[index] = { ...form.value }
      }

      nextTick(() => {
        isNew.value = true
        drawerRef.value?.closeDrawer()
        resetForm(ruleFormRef.value)
		emit('onPlanning', tableData.value)
      })
    }
  })
}
const emit = defineEmits<{ (event: 'onPlanning', value: any): void }>()
const getDetailInfo = () => tableData.value
const clearDetail = () => (tableData.value = [])
const setDetailData = (info: any[]) => {
  tableData.value = info.map((item: any) => {
    item.id = generateRandom()
    return item
  })
}
defineExpose({
  getDetailInfo,
  clearDetail,
  setDetailData
})
const props = defineProps<{ disabled: boolean; isShow?: string;typeTip?:string }>()
const disabled = computed(() => props.disabled)
const isShow = ref(props.isShow)
const typeTip = ref(props.typeTip)
</script>

<template>
  <el-table
    stripe
    :data="tableData"
    style="width: 100%"
    :header-cell-style="{
      background: 'rgb(225 226 228)',
      color: '#000'
    }"
  >
    <template v-for="item in columns" :key="item.prop">

		<el-table-column
			v-if="item.prop === 'T_state'"
			:label="item.label"
			:width="item.width"
			align="center"
		>
			<template v-slot="scope">
				<el-text v-if="scope.row.T_state === 1" effect="dark">待采购</el-text>
				<el-text v-else type="success" effect="dark">已采购</el-text>
			</template>
		</el-table-column>
      <el-table-column show-overflow-tooltip v-bind="item" v-else-if="item.type === 'index'"></el-table-column>
      <el-table-column show-overflow-tooltip v-bind="item" v-else-if="item.fixed !== 'right' && item.type !== 'index'"> </el-table-column>
      <el-table-column show-overflow-tooltip v-bind="item" v-else-if="item.fixed === 'right'">
        <template #default="{ row }">
          <el-button size="small" :disabled="typeTip === 'view'" type="primary" @click="openProductionDetailed('edit', row)"
            >编辑</el-button
          >
          <el-button size="small" :disabled="isShow !== 'myPurchase' || typeTip === 'view'" type="danger" @click="deletePurchaseDetail(row.id)"
            >删除</el-button>
        </template>
      </el-table-column>
    </template>
    <template #append v-if="isShow === 'myPurchase'">
      <el-button type="primary" :disabled="disabled" @click="openProductionDetailed('new')">
        <el-icon><Plus /></el-icon><span style="margin-left: 6px">添加</span>
      </el-button>
    </template>
  </el-table>
  <Drawer ref="drawerRef" :handleClose="callbackDrawer">
    <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_name">
        <el-input v-model="form.T_name" type="text" autocomplete="off" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="型号：" :label-width="formLabelWidth" prop="T_model">
        <el-input v-model="form.T_model" type="text" autocomplete="off" placeholder="请输入型号" />
      </el-form-item>
      <el-form-item label="规格：" :label-width="formLabelWidth" prop="T_spec">
        <el-input v-model="form.T_spec" type="text" autocomplete="off" placeholder="请输入规格" />
      </el-form-item>
		<el-form-item label="数量：" :label-width="formLabelWidth" prop="T_quantity">
			<el-input v-model="form.T_quantity" type="text" autocomplete="off" placeholder="请输入数量" />
		</el-form-item>
		<el-form-item label="参考网址：" :label-width="formLabelWidth" prop="T_reference_site">
			<el-input v-model="form.T_reference_site" type="text" autocomplete="off" placeholder="请输入参考网址" />
		</el-form-item>
		<el-form-item label="需求：" :label-width="formLabelWidth" prop="T_demand">
			<el-input v-model="form.T_demand" type="text" autocomplete="off" placeholder="请输入需求" />
		</el-form-item>
		<el-form-item label="备注：" :label-width="formLabelWidth" prop="T_remark">
			<el-input v-model="form.T_remark" type="text" autocomplete="off" placeholder="请输入备注" />
		</el-form-item>
		<el-form-item v-if="isShow !== 'myPurchase'" label="状态：" :label-width="formLabelWidth" prop="T_state">
			<el-radio-group v-model="form.T_state">
				<el-radio :label="1">待采购</el-radio>
				<el-radio :label="2">已采购</el-radio>
			</el-radio-group>
		</el-form-item>
		<el-form-item v-if="isShow !== 'myPurchase'" label="采购时间：" :label-width="formLabelWidth" prop="T_date">
			<el-date-picker
				style="flex: 0 0 50%"
				class="my-date-picker"
				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_unit_price">
			<el-input v-model="form.T_unit_price" type="text" autocomplete="off" placeholder="请输入采购单价" />
		</el-form-item>
		<el-form-item v-if="isShow !== 'myPurchase'" label="采购金额：" :label-width="formLabelWidth" prop="T_amount">
			<el-input v-model="form.T_amount" type="text" autocomplete="off" placeholder="请输入采购金额" />
		</el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-button v-if="isNew" class="btn"  type="primary" @click="addPurchaseDetail(ruleFormRef)"
          >添加</el-button
        >
        <el-button v-else class="btn" type="primary" @click="addPurchaseDetail(ruleFormRef)"
          >修改</el-button
        >
      </el-form-item>
    </el-form>
  </Drawer>
</template>

<style scoped lang="scss">
:deep(.el-drawer__body .el-table .cell) {
  white-space: normal !important;
}
.el-form-item {
  margin-bottom: 18px;
}
</style>
