<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import Dialog from '@/components/dialog/Dialog.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { GlobalStore } from '@/stores/index'
import Upload from '@/components/Upload/index.vue'
import {
  Storehouse_Contract_Add,
  Storehouse_Product_List,
  Storehouse_Contract_Edit,
  Storehouse_ProductClass_List,
  Storehouse_Product_Model_List,
  Storehouse_Product_Name_List,
  Storehouse_Contract_Product_List
} from '@/api/storehouse/index'
import { ElMessage } from 'element-plus'
import { default as vElTableInfiniteScroll } from 'el-table-infinite-scroll'

let selectProductData: any[] = []
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 selectTable = ref()
const drawerProductRef = ref<InstanceType<typeof Drawer> | null>(null)

const validate_T_product = (rule: any, value: any, callback: any) => {
  if (form.T_type === 1 && value === '') {
    callback(new Error('请选择产品明细'))
  } else if (value.includes(undefined)) {
    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)
  isNew.value = true
  done()
}
const callbackProductDrawer = (done: Fn) => done()

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

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

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

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) => {
  // console.log(row)
  // form.T_id = row.Id
  form.T_pdf = row.T_pdf
  form.T_date = row.T_date
  form.T_type = row.T_type
  form.T_money = row.T_money
  form.T_remark = row.T_remark
  form.T_number = row.T_number
  form.T_customer = row.T_customer

  const res: any = await Storehouse_Contract_Product_List({
    User_tokey: globalStore.GET_User_tokey,
    T_number: row.T_number
  })
  if (res.Code === 200) {
    res.Data &&
      (tableData.value = res.Data.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
  }
}

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)

  // 设置产品的选中
  selectTable.value?.toggleRowSelection(row, false)
}

const AddContract = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      let product = ''
      tableData.value.forEach(item => {
        product += `${item.Id},${item.count}|`
      })
      if (isNew.value) {
        res = await Storehouse_Contract_Add({
          ...form,
          User_tokey: globalStore.GET_User_tokey,
          T_product: product
        })
      } else {
        res = await Storehouse_Contract_Edit({
          ...form,
          T_product: product,
          User_tokey: globalStore.GET_User_tokey
        })
      }
      if (res.Code === 200) {
        ElMessage.success(`${isNew.value ? '添加' : '修改'}合同成功！！`)
        nextTick(() => {
          drawerRef.value?.closeDrawer()
          emit('onTableList')
          resetForm(ruleFormRef.value)
          isNew.value = true
        })
      }
    } else {
      return false
    }
  })
}

// 增加产品
// dialog
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_model: '',
  T_class: '',
  page: 0,
  page_z: 20
})
const classOptions = ref<any[]>([])
const modelOptions = ref<any[]>([])
// 获取产品分类
const getProductClassList = async () => {
  const res: any = await Storehouse_ProductClass_List({ page: 1, page_z: 999 })
  classOptions.value = res.Data.Data
}
// 获取产品型号
const getProductModelList = async () => {
  const res: any = await Storehouse_Product_Model_List({ T_name: autoSelect.value })
  modelOptions.value = res.Data.map((item: any, index: number) => {
    return {
      value: item,
      index: index
    }
  })
}
const AddProductionDetailed = () => {
  // getProductList()
  !classOptions.value.length && getProductClassList()
  drawerProductRef.value?.openDrawer()
}

// 搜索模型
const searchModelHandle = () => {
  total = 0
  initParam.page = 1
  tableProductData.value = []
  getProductList()
}
// 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
const getRowKey = (row: any) => {
  return row.Id
}
// 选中的产品
const ProductselectionChange = (row: any[]) => {
  if (!isNew.value) {
    const newProduct = row.find(
      (product: any) => tableData.value.findIndex((item: any) => item.Id === product.Id) === -1
    )
    newProduct && tableData.value.push({ ...newProduct })
  } else {
    tableData.value = row
  }
}

// 加载第二个抽屉数据
const load = () => {
  if (initParam.page && total === tableProductData.value.length) {
    ElMessage.warning('没有更多数据了！！')
    return
  }
  initParam.page++
  getProductList()
}
let total = 0
const tableProductData = ref<any[]>([])
const getProductList = async () => {
  const res: any = await Storehouse_Product_List({ ...initParam, T_name: autoSelect.value })
  tableProductData.value.push(...res.Data.Data)
  total = res.Data.Num
  if (!isNew.value) {
    // 设置产品的选中
    tableProductData.value.forEach((row: any) => {
      const matchedIndex = selectProductData.findIndex((item: any) => item.Id == row.Id)

      selectTable.value?.toggleRowSelection(row, matchedIndex != -1)
    })
  }
}

const tableData = ref<any[]>([])
const columns = [
  { type: 'index', label: '序号', width: 80, align: 'center ' },
  { label: '产品图片', prop: 'T_img', align: 'center ', name: 'T_img' },
  { 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, name: 'T_relation_sn' },
  { label: '*数量', prop: 'count', align: 'center ', name: 'count' },
  { 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: '产品型号', ellipsis: true },
  { prop: 'T_spec', label: '产品规格' },
  { prop: 'T_relation_sn', label: '关联SN', name: 'T_relation_sn' },
  { prop: 'T_remark', label: '备注', ellipsis: true }
]

// 自动搜索
const autoSelect = ref('')
let timeout: NodeJS.Timeout
const querySearchAsync = async (queryString: string, cb: (arg: any) => void) => {
  clearTimeout(timeout)
  timeout = setTimeout(async () => {
    const results = await getNameAsync(queryString)
    console.log(autoSelect, queryString)
    cb(results)
  }, 2000)
}

const getNameAsync = async (str: string): Promise<any> => {
  const res: any = await Storehouse_Product_Name_List({ T_name: str, T_class: initParam.T_class })
  if (!res.Data) return
  return res.Data.map((item: any, index: number) => {
    return {
      value: item,
      index: index
    }
  })
}

const handleSelect = (item: any) => {
  console.log(item, autoSelect.value)
  // initParam.T_name = item.value
  getProductModelList()
}

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"
            :disabled="!isNew"
            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 :disabled="!isNew" 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">
                  <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>
                  <el-image v-if="item.prop === 'T_img'" style="height: 50px" :src="row.T_img" fit="cover" />
                </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_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_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>

        <div class="btn">
          <el-divider>
            <el-button>取消</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>
          </el-divider>
        </div>
        <Drawer ref="drawerProductRef" :handleClose="callbackProductDrawer" size="70%">
          <template #header="{ params }">
            <h4 :id="params.titleId" :class="params.titleClass">选择产品</h4>
          </template>
          <el-card class="box-card" shadow="never">
            <template #header>
              <div class="input-suffix">
                <el-row :gutter="20" style="margin-bottom: 0">
                  <el-col :xl="5" :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="7" :lg="8" :md="10" class="d-flex">
                    <span class="inline-flex items-center">产品名称：</span>
                    <el-autocomplete
                      v-model="autoSelect"
                      clearable
                      :fetch-suggestions="querySearchAsync"
                      placeholder="Please input"
                      :debounce="2000"
                      :trigger-on-focus="false"
                      @select="handleSelect"
                    />
                  </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.index"
                        :label="item.value"
                        :value="item.index"
                      />
                    </el-select>
                    <el-button type="primary" @click="searchModelHandle">搜索</el-button>
                  </el-col>
                </el-row>
              </div>
            </template>
            <el-table
              ref="selectTable"
              :row-key="getRowKey"
              :data="tableProductData"
              style="width: 100%; height: 99%"
              v-el-table-infinite-scroll="load"
              @selection-change="ProductselectionChange"
            >
              <template v-for="item in productColumns" :key="item">
                <el-table-column
                  v-if="item.type === 'index' || item.type === 'selection'"
                  align="center"
                  v-bind="item"
                />
                <el-table-column v-if="!item.ellipsis && item.prop" v-bind="item">
                  <template #default="{ row }">
                    <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>
                    <el-image v-if="item.prop === 'T_img'" style="height: 50px" :src="row.T_img" fit="cover" />
                  </template>
                </el-table-column>
                <el-table-column v-if="item.ellipsis && item.prop === 'T_model'" align="center" v-bind="item">
                  <template #default="{ row }">
                    <el-tooltip effect="dark" :content="row.T_model" placement="bottom">
                      {{ row.T_model }}
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column v-if="item.ellipsis && item.prop === 'T_remark'" align="center" v-bind="item">
                  <template #default="{ row }">
                    <el-tooltip effect="customized" placement="left">
                      <template #content>
                        <div class="tooltip-content">{{ row.T_remark }}</div>
                      </template>
                      {{ row.T_remark }}
                    </el-tooltip>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </el-card>
        </Drawer>
      </el-form>
    </Drawer>
  </div>
</template>

<style scoped lang="scss">
.tooltip-content {
  max-width: 500px;
  overflow-y: auto;
}
.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;
  }
  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
    .d-flex {
      display: flex;
    }
  }
}
</style>
