<script setup lang="ts">
import { ref, reactive } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import Dialog from '@/components/dialog/Dialog.vue'
import type { FormInstance, FormRules } from 'element-plus'
// import type { TableColumnCtx } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { GlobalStore } from '@/stores/index'
import TableBase from '@/components/TableBase/index.vue'
import Upload from '@/components/Upload/index.vue'
import { Storehouse_Product_List } from '@/api/storehouse/index'
// import { Storehouse_IotCard_Add, Storehouse_IotCard_Edit } from '@/api/storehouse/index'

const isNew = ref(true)
const globalStore = GlobalStore()
const formLabelWidth = ref('120px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const dialogRef = ref<InstanceType<typeof Dialog> | null>(null)
const uploadRef = ref<InstanceType<typeof Upload> | null>(null)
const TableProductRef = ref<InstanceType<typeof TableBase> | null>(null)

const validate_T_product = (rule: any, value: any, callback: any) => {
  if (form.T_type === 1 && value === '') {
    callback(new Error('请选择产品明细'))
  } else {
    callback()
  }
}

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_date: [{ required: true, message: '请选择业务日期', trigger: 'blur' }]
})

const callbackDrawer = (done: Fn) => {
  resetForm(ruleFormRef.value)
  done()
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 添加仓库名称
type Fn = () => void
const form = reactive({
  T_id: '',
  T_number: '',
  T_customer: '',
  T_type: null,
  T_product: '',
  T_money: '',
  T_date: '',
  T_remark: '',
  T_pdf: ''
})

const openDrawer = (type: string, row?: any) => {
  console.log(type, row)
  isNew.value = type === 'new' ? true : false
  // nextTick(() => {
  //   form.T_id = row.Id
  //   form.T_sn = row.T_sn
  //   form.T_type = row.T_type
  //   form.T_state = row.T_State
  //   form.T_iccid = row.T_iccid
  // })
  drawerRef.value?.openDrawer()
}

// const AddUserName = (formEl: FormInstance | undefined) => {
//   if (!formEl) return
//   formEl.validate(async valid => {
//     if (valid) {
//       let res: any = {}
//       if (isNew.value) {
//         console.log(form)
//         res = await Storehouse_IotCard_Add({ User_tokey: globalStore.GET_User_tokey, ...form })
//       } else {
//         res = await Storehouse_IotCard_Edit({
//           User_tokey: globalStore.GET_User_tokey,
//           ...form
//         })
//       }
//       if (res.Code === 200) {
//         ElMessage.success(`${isNew.value ? '添加' : '修改'}物联网卡成功！！`)
//         nextTick(() => {
//           drawerRef.value?.closeDrawer()
//           TableRef.value?.getTableList()
//           resetForm(ruleFormRef.value)
//           isNew.value = true
//         })
//       }
//     } else {
//       return false
//     }
//   })
// }

// const AddUserName = () => {
//   console.log(tableData)
// }
// 增加产品
// dialog
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_model: '',
  T_class: ''
})
const classOptions = reactive<any[]>([])
const modelOptions = reactive<any[]>([])
const AddProductionDetailed = () => {
  dialogRef.value?.DialogOpen()
}
const searchHandle = () => {
  //
}

const tableData = reactive<any[]>([])
const columns = [
  { type: 'index', label: '序号', width: 80, align: 'center ' },
  { label: '产品图片', prop: 'T_img', align: 'center ' },
  { label: '产品名称', prop: 'T_name', align: 'center ' },
  { label: '产品分类', prop: 'T_class_name', align: 'center ' },
  { label: '产品型号', prop: 'T_model', align: 'center ' },
  { label: '产品规格', prop: 'T_spec', align: 'center ' },
  { label: '是否关联SN', prop: 'T_relation_sn', align: 'center ', width: 120 },
  { label: '*数量', prop: 'count', align: 'center ', name: 'count' },
  { label: '备注', prop: 'id', align: 'center ' },
  { prop: 'operation', label: '操作', width: 80, fixed: 'right' }
]

const productColumns = [
  { type: 'selection', width: 80 },
  { prop: 'T_img', label: '产品图片', name: 'T_img' },
  { prop: 'T_name', label: '产品名称' },
  { prop: 'T_class_name', label: '产品分类' },
  { prop: 'T_model', label: '产品型号' },
  { prop: 'T_spec', label: '产品规格' },
  { prop: 'T_relation_sn', label: '关联SN', name: 'T_relation_sn' },
  { prop: 'T_name', label: '更新时间' }
]

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-divider border-style="dashed" />
        <el-form-item label="合同编号：" :label-width="formLabelWidth" prop="T_number">
          <el-input
            v-model="form.T_number"
            type="text"
            autocomplete="off"
            placeholder="请输入物联网卡号"
            class="w-50"
          />
        </el-form-item>
        <el-form-item label="客户名称：" :label-width="formLabelWidth" prop="T_customer">
          <el-input v-model="form.T_customer" type="text" autocomplete="off" placeholder="请输入型号" class="w-50" />
        </el-form-item>
        <el-form-item label="合同类型：" :label-width="formLabelWidth" prop="T_type">
          <el-select v-model="form.T_type" class="w-50" clearable placeholder="请选择~">
            <el-option label="销售合同" :value="1" />
            <el-option label="验证合同" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品明细：" :label-width="formLabelWidth" prop="T_product">
          <el-table
            :data="tableData"
            style="width: 100%"
            border
            stripe
            :header-cell-style="{
              background: '#909399',
              height: '50px',
              color: '#fff'
            }"
          >
            <template v-for="item in columns" :key="item.prop">
              <el-table-column 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 && item.prop">
                  <el-input v-model.number="row.count" type="text" autocomplete="off" />
                </template>
              </el-table-column>
              <el-table-column v-bind="item" v-if="item.fixed === 'right'">
                <el-button link type="danger" size="small" :icon="Delete">删除</el-button>
              </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_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_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_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_type">
          <Upload
            class="w-50"
            ref="uploadRef"
            :isImg="true"
            :limit="1"
            v-model="form.T_pdf"
            accept=".pdf"
            listType="text"
          >
            <el-button type="primary">上传文件</el-button>
            <template #tip> 只能上传pdf格式文件!!</template>
          </Upload>
        </el-form-item>

        <div class="btn">
          <el-divider>
            <el-button>取消</el-button>
            <el-button v-if="isNew" color="#626aef">提交</el-button>
            <el-button v-else color="#626aef">修改</el-button>
          </el-divider>
        </div>
      </el-form>
    </Drawer>
    <Dialog ref="dialogRef" width="80%">
      <template #header> 选择产品 </template>
      <TableBase
        ref="TableProductRef"
        :columns="productColumns"
        :requestApi="Storehouse_Product_List"
        :initParam="initParam"
      >
        <template #table-header>
          <div class="input-suffix">
            <el-row :gutter="20" style="margin-bottom: 0">
              <el-col :xl="6" :lg="8" :md="10" class="d-flex">
                <span class="inline-flex items-center">产品分类：</span>
                <el-select v-model="initParam.T_class" clearable placeholder="请选择分类~">
                  <el-option v-for="item in classOptions" :key="item.Id" :label="item.T_name" :value="item.Id" />
                </el-select>
              </el-col>
              <el-col :xl="6" :lg="8" :md="10" class="d-flex">
                <span class="inline-flex items-center">产品名称：</span>
                <el-input
                  v-model="initParam.T_name"
                  type="text"
                  placeholder="按产品名称、产品型号搜索"
                  @change="searchHandle"
                />
              </el-col>
              <el-col :xl="7" :lg="8" :md="12" class="d-flex">
                <span class="inline-flex items-center">产品型号：</span>
                <el-select v-model="initParam.T_model" clearable placeholder="请选择型号~">
                  <el-option v-for="item in modelOptions" :key="item.Id" :label="item.T_name" :value="item.Id" />
                </el-select>
                <el-button type="primary" @click="searchHandle">搜索</el-button>
              </el-col>
            </el-row>
          </div>
        </template>
        <template #T_img="{ row }">
          <el-image style="height: 50px" :src="row.T_img" fit="cover" />
        </template>
        <template #T_relation_sn="{ row }">
          <el-tag v-if="row.T_relation_sn === 1" effect="dark">是</el-tag>
          <el-tag v-else type="success" effect="dark">否</el-tag>
        </template>
      </TableBase>
    </Dialog>
  </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;
  }
  .btn {
    margin-top: 32px;
    display: flex;
    justify-content: center;
    .el-button {
      padding: 0 32px;
    }
  }
  .w-50 {
    width: 21.5rem;
  }
  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
    .d-flex {
      display: flex;
    }
  }
}
</style>
