<template>
  <div class="h-full flex">
    <div class="p-5 w-80 pr-0">
      <div class="bg-white w-full h-full shadow-md rounded-md flex flex-col">
        <div class="flex-1 p-3 overflow-y-auto">
          <el-form :model="filterProductForm" label-width="70px" style="max-width: 600px">
            <el-form-item label="产品编号">
              <el-input v-model="filterProductForm.productCode" clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="产品名称">
              <el-input v-model="filterProductForm.productName" clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="产品类别">
              <el-select v-model="filterProductForm.type" placeholder="请选择" clearable>
                <el-option v-for="item in fixedData.ProductType" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="filterProductForm.status" placeholder="请选择">
                <el-option v-for="item in fixedData.Personnel" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="负责人">
              <el-select v-model="filterProductForm.userId" placeholder="请选择">
                <el-option v-for="item in fixedData.Personnel" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker v-model="filterProductForm.startTime" type="date" placeholder="请选择" :clearable="false"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="">
              <el-date-picker v-model="filterProductForm.endTime" type="date" placeholder="请选择" :clearable="false"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-form>
        </div>
        <div class="w-full flex p-3 shadow-[0_-3px_5px_0px_rgba(0,0,0,0.2)]">
          <El-button class="w-full" @click="resetFilter()">重置</El-Button>
          <El-button type="primary" class="w-full" @click="getProductTableList()">搜索</El-Button>
        </div>
      </div>
    </div>
    <div class="flex-1 p-5 overflow-auto">
      <div class="bg-white w-full h-full p-3 shadow-md rounded-md flex flex-col">
        <div class="flex justify-end pb-3">
          <el-button type="primary" @click="editProduct(false)">新建产品</el-button>
          <el-button type="primary" @click="batchDelete()">批量删除</el-button>
          <el-button type="primary" @click="showDeteleProduct(true)">回收站</el-button>
          <el-button type="primary" @click="dialogVisible.importVisible = true">导入</el-button>
          <el-button type="primary" @click="exportProductTableList()" :loading="allLoading.exoprtLoading">导出</el-button>
        </div>
        <div class="flex-1 w-full overflow-hidden">
          <el-table ref="productTableRef" :data="productTableList" border v-loading="allLoading.productTableLading"
            style="width: 100%;height: 100%;">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="productCode" label="产品编号" width="180"></el-table-column>
            <el-table-column prop="productName" label="产品名称" width="180">
              <template #default="scope">
                <el-button link type="primary" size="large" @click="toProductDetail(scope.row)">{{
                  scope.row.productName
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="typeName" label="产品类别" width="180"></el-table-column>
            <el-table-column prop="unitName" label="单位" width="180"></el-table-column>
            <el-table-column prop="price" label="标准价格(元)" width="180"></el-table-column>
            <el-table-column prop="inventory" label="库存" width="180"></el-table-column>
            <el-table-column prop="status" label="状态" width="180">
              <template #default="scope">
                {{ scope.row.status == 1 ? '上架' : '下架' }}
              </template>
            </el-table-column>
            <el-table-column prop="inchargerName" label="负责人" width="190"></el-table-column>
            <el-table-column prop="creatorName" label="创建人" width="180"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
            <el-table-column label="操作" fixed="right" width="200">
              <template #default="scope">
                <el-button link type="primary" size="large" @click.stop="editProduct(scope.row)">编辑</el-button>
                <el-button link type="danger" size="large" @click.stop="deteleRow([scope.row])">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex justify-end pt-3">
          <el-pagination layout="total, prev, pager, next, sizes" :page-size="filterProductForm.pageSize"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" :total="productTableTotal"
            :hide-on-single-page="true" />
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible.editProductVisible" width="1000" :show-close="false" top="10vh">
      <template #header="{ close, titleId, titleClass }">
        <div class="flex justify-between items-center border-b pb-3 dialog-header">
          <h4 :id="titleId">{{ allText.editClueText }}</h4>
          <div>
            <el-button type="primary" @click="saveProductRow(true)" :loading="allLoading.saveLoading">保存并新建</el-button>
            <el-button type="primary" @click="saveProductRow(false)" :loading="allLoading.saveLoading">保存</el-button>
            <el-button @click="dialogVisible.editProductVisible = false">取消</el-button>
          </div>
        </div>
      </template>
      <div class="h-[60vh] overflow-y-auto scroll-bar pt-3" v-loading="allLoading.generateFormLading">
        <div class="ml-4 mr-4">
          <GenerateForm ref="generateForm" :data="productTemplate" :value="genereditForm" :key="generateFormKey" />
        </div>
      </div>
    </el-dialog>

    <el-dialog v-model="dialogVisible.importVisible" width="680" :show-close="false" top="10vh">
      <template #header="{ close, titleId, titleClass }">
        <div class="flex justify-between items-center border-b pb-3 dialog-header">
          <h4 :id="titleId">导入产品</h4>
          <div class="flex">
            <el-upload class="upload-demo mr-3" :limit="1" :show-file-list="false" accept=".xlsx" :http-request="importProducts">
              <el-button type="primary" :loading="allLoading.importLoading">导入</el-button>
            </el-upload>
            <el-button @click="dialogVisible.importVisible = false">取消</el-button>
          </div>
        </div>
      </template>
      <div class="p-8">
        <div class="ml-4 mr-4">
          <div class="flex items-center">1、点击下载 <el-link type="primary" @click="downloadTemplate(MODUCODE, '产品导入模板.xlsx')">产品导入模板.xlsx</el-link></div>
          <div class="mt-4">2、填写excel文件、产品编号、产品名称、产品类别、标准价格、库存、状态必填</div>
        </div>
      </div>
    </el-dialog>

    <DeteleTables :visibles="dialogVisible.deteleProductDialogVisible" @showDeteleProduct="showDeteleProduct" />

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from "vue";
import { GETSYSFILED, MOD, MODUCODE, GETPERSONNEL, GETTEMPLATE, GETTABLELIST, ADDPRODUCT, ALLDETELE, UPLOADFILE, EXPORTTIME } from './api'
import { getAllListByCode, getFromValue, resetFromValue, getFirstDayOfMonth, downloadFile, formatDate, createTaskFromType, confirmAction, downloadTemplate } from '@/utils/tools'
import { FormInstance, FormRules, ElMessageBox, ElTable, UploadRequestOptions } from 'element-plus'
import { post, get, uploadFile } from "@/utils/request";
import { useRouter, useRoute } from "vue-router";
import { GenerateForm } from '@zmjs/form-design';
import DeteleTables from "./deteleTables.vue";

const router = useRouter()
const globalPopup = inject<GlobalPopup>('globalPopup')
const filterProductForm = reactive<filterProductFormType>({ // 筛选条件form
  userId: '',
  productName: '',
  productCode: '',
  startTime: getFirstDayOfMonth(new Date()),
  endTime: formatDate(new Date()),
  pageIndex: 1,
  pageSize: 10,
  id: '',
  type: '',
  status: '',
})
const allLoading = reactive({
  productTableLading: false,
  generateFormLading: false,
  saveLoading: false,
  importLoading: false,
  exoprtLoading: false
})
const dialogVisible = reactive({
  editProductVisible: false,
  taskModalVisible: false,
  clueDialogVisible: false,
  deteleClueDialogVisible: false,
  importVisible: false,
  deteleProductDialogVisible: false
})
const allText = reactive({
  editClueText: '新建产品',
})
const fixedData = reactive({
  ProductType: [] as fixedDataInterface[],
  Personnel: [] as personnelInterface[]
})
const productTableList = ref([]) // 产品table数据
const productTableTotal = ref(0) // 产品 table 数据总数
const productTableRef = ref<InstanceType<typeof ElTable>>() // 产品table dom
const generateForm: any = ref(null) // 模板
const productTemplate = ref({
  list: [],
  config: {}
}) // 产品模板
const genereditForm = ref({}) // 编辑表单
const generateFormKey = ref(1)

// 方法定义
function batchDelete() {
  const data = productTableRef.value && productTableRef.value.getSelectionRows()
  if (!data.length) {
    globalPopup?.showWarning('请选择数据')
    return
  }
  deteleRow(data)
}

function showDeteleProduct(flag: boolean) {
  if(!flag) {
    getProductTableList()
  }
  dialogVisible.deteleProductDialogVisible = flag
}

function deteleRow(items: any[]) {
  let ids = items.map(item => item.id).join(',')
  let str = items.map(item => item.productName).join(',')
  confirmAction(`确定${items.length > 1 ? '批量删除' : '删除'}【${str}】产品吗？`).then(() => {
    post(ALLDETELE, { ids: ids }).then((_res) => {
      globalPopup?.showSuccess('删除成功')
      getProductTableList()
    }).catch((err) => {
      globalPopup?.showError(err.msg)
    })
  })
}

async function saveProductRow(flag: boolean) {
  const data = await generateForm.value.getData()
  let newData = { ...genereditForm.value, ...data }
  delete newData.createTime
  allLoading.saveLoading = true
  post(ADDPRODUCT, { ...newData }).then(() => {
    globalPopup?.showSuccess('保存成功')
    if (flag) {
      genereditForm.value = {}
      generateForm.value && generateForm.value.reset()
    }
    getProductTableList()
    dialogVisible.editProductVisible = flag
  }).catch((err) => {
    globalPopup?.showError(err.msg)
  }).finally(() => {
    allLoading.saveLoading = false
  })
}

function editProduct(item: any) {
  dialogVisible.editProductVisible = true
  allLoading.generateFormLading = true
  if (item) {
    genereditForm.value = item
    allText.editClueText = '编辑产品'
  }
  if (!item) {
    genereditForm.value = {}
  }
  setTimeout(() => {
    generateForm.value && generateForm.value.reset()
    generateFormKey.value++
    allLoading.generateFormLading = false
  }, 500)
}

function getProductTableList() {
  allLoading.productTableLading = true
  let valueForm = getFromValue(filterProductForm)
  post(GETTABLELIST, { ...valueForm }).then((res) => {
    if (res.code == 'ok') {
      const { record, total } = res.data
      productTableList.value = record
      productTableTotal.value = total
    }
  }).finally(() => {
    allLoading.productTableLading = false
  })
}

async function importProducts(param: UploadRequestOptions) {
  allLoading.importLoading = true
  const formData = new FormData();
  formData.append('multipartFile', param.file)
  const res = await uploadFile(UPLOADFILE, formData)
  allLoading.importLoading = false
  if (res.code == 'ok') {
    globalPopup?.showSuccess('导入成功' || '')
    getProductTableList()
    return
  }
  globalPopup?.showError(res.msg || '')
}

function exportProductTableList() {
  allLoading.exoprtLoading = true
  let valueForm = getFromValue(filterProductForm)
  post(EXPORTTIME, {...valueForm}).then((res) => {
    downloadFile(res.data, '产品表导出.xlsx')
  }).finally(() => {
    allLoading.exoprtLoading = false
  })
}

function handleSizeChange(val: number) {
  filterProductForm.pageIndex = 1
  filterProductForm.pageSize = val
  getProductTableList()
}

function handleCurrentChange(val: number) {
  filterProductForm.pageIndex = val
  getProductTableList()
}

function resetFilter() {
  let newResetForm = resetFromValue(filterProductForm, { startTime: getFirstDayOfMonth(new Date()), endTime: formatDate(new Date()), pageIndex: 1, pageFrom: 10 })
  Object.assign(filterProductForm, newResetForm)
  getProductTableList()
}

function toProductDetail(row: any) {
  router.push({
    path: `${MOD}/detail`,
    query: { id: row.id }
  })
}

async function getSystemField() {
  const systemField = getAllListByCode(['产品类型'])
  for (let i in systemField) {
    const { data } = await get(`${GETSYSFILED}?code=${systemField[i]}`)
    for (let key of Object.keys(fixedData)) {
      if (systemField[i] == key) {
        Object.assign(fixedData, { [key]: data })
      }
    }
  }

  const { data } = await post(GETPERSONNEL, {})
  fixedData.Personnel = data.map((item: any) => {
    const { id, name, phone, jobNumber } = item
    return {
      id, name, phone, jobNumber
    }
  })

  const res = await get(GETTEMPLATE)
  productTemplate.value = JSON.parse(res.data[0].config)
}

onMounted(() => {
  getSystemField()
  getProductTableList()
})
</script>

<style lang="scss" scoped></style>