<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="filterForm" label-width="70px" style="max-width: 600px">
            <template v-for="(item, index) in filterItems">
              <el-form-item :label="item.label" v-if="item.type != 'date'">
                <el-input v-if="item.type === 'input'" v-model="filterForm[item.key as keyof FilterForm]" clearable
                  placeholder="请输入"></el-input>
                <template v-else-if="['inchargerId'].includes(item.key)">
                  <personnel-search v-model="filterForm[item.key as keyof FilterForm]" :size="''" placeholder="请选择"></personnel-search>
                </template>
                <el-select v-else v-model="filterForm[item.key as keyof FilterForm]" placeholder="请选择" clearable>
                  <el-option v-for="option in item.options" :key="option.id" :label="option.name" :value="option.id" />
                </el-select>
              </el-form-item>
              <template v-if="item.type == 'date'">
                <el-form-item :label="item.label">
                  <el-date-picker v-model="filterForm.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="filterForm.endTime" type="date" placeholder="请选择" :clearable="false"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </el-form-item>
              </template>
            </template>
          </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="resetFilterForm()">重置</El-Button>
          <El-button type="primary" class="w-full" @click="getTableList()">搜索</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" v-permission="['orderAdd']" @click="editOrder(false)">新建订单</el-button>
          <!-- <el-button type="primary" :disabled="batchTableData.length <= 0">批量转移</el-button> -->
          <el-button type="primary" v-permission="['orderDelete']" @click="batchDeteleItem()" :disabled="batchTableData.length <= 0">批量删除</el-button>
          <el-button type="primary" v-permission="['orderRecycle']" @click="showVisible('deteleOrderVisible')">回收站</el-button>
          <el-button type="primary" v-permission="['orderImport']" @click="showVisible('importVisible')">导入</el-button>
          <el-button type="primary" v-permission="['orderExport']" @click="exportOrderTableList()" :loading="allLoading.exoprtLoading">导出</el-button>
        </div>
        <div class="flex-1 w-full overflow-hidden">
          <!-- 表格 -->
          <el-table ref="otherTableRef" :data="formTable" :show-overflow-tooltip="tableShowOverflowTooltip" border v-loading="allLoading.formTableLading"
            style="width: 100%;height: 100%;" @selection-change="changeBatch">
            <el-table-column type="selection" width="55" />
            <el-table-column v-for="(column, index) in tableColumns" :key="index" :prop="column.prop"
              :label="column.label" :width="column.width">
              <template #default="scope">
                <template v-if="column.event === 'toDetali'">
                  <!-- <el-button link type="primary" size="large" @click="toDetali(scope.row)">{{ scope.row[column.prop]
                  }}</el-button> -->
                  <div class="table-text-textnowrap" @click.prevent="toDetali(scope.row)">{{ scope.row[column.prop] }}</div>
                </template>
                <template v-if="['customSignerName', 'companySignerName', 'inchargerName', 'creatorName'].includes(column.prop)">
                  <TextTranslation translationTypes="userName" :translationValue="scope.row[column.prop]" v-if="scope.row[column.prop]"></TextTranslation>
                </template>
                <template v-if="column.prop === 'receivedStatus'">
                  <div>{{ selectData.RemittanceStatus[scope.row.receivedStatus].name }}</div>
                </template>
              </template>
            </el-table-column>
            <el-table-column :label="'操作'" :width="'200px'" fixed="right" v-permission="['orderEdit']">
              <template #default="scope">
                <el-button link type="primary" size="large" @click="editOrder(scope.row)">编辑</el-button>
                <el-button link type="primary" size="large" v-permission="['tasksEdit']" @click="newTask(scope.row)">新建任务</el-button>
                <el-button link type="danger" size="large" v-permission="['orderDelete']"
                  @click="orderDeteleItem(scope.row.id, scope.row.orderName)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex justify-end pt-3">
          <!-- 分页 -->
          <el-pagination layout="total, prev, pager, next, sizes" :total="formTablePaging.total"
            :hide-on-single-page="true" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="allVisible.editOrderVisible" 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.orderEditText }}</h4>
          <div>
            <el-button type="primary" :loading="allLoading.editSaveLading" v-if="!orderTemplateValue.id" @click="saveOrder(true)">保存并新建</el-button>
            <el-button type="primary" :loading="allLoading.editSaveLading" @click="saveOrder(false)">保存</el-button>
            <el-button @click="closeVisible('editOrderVisible')">取消</el-button>
          </div>
        </div>
      </template>
      <div class="h-[60vh] overflow-y-auto scroll-bar pt-3" v-loading="allLoading.orderTemplateLoadinng">
        <GenerateForm ref="orderTemplateRef" :data="orderTemplate" :key="orderTemplateKey" :value="orderTemplateValue" />
        <div>相关产品</div>
        <RelatedProducts ref="relatedProductsRef" :productTableList="productTableList"
          :productTableListValue="productTableListValue"  />
      </div>
    </el-dialog>

    <!-- 新建任务 -->
    <TaskModal :visible="allVisible.taskModalVisible" :edit-form="taskModalForm" :save-loading="taskLoading"
      @close="allVisible.taskModalVisible = false" @submit="submitForm" :title="'新建任务'"
      :disabled-list="['taskType', 'orderId']" />

    <!-- 回收站 -->
    <DeteleTables :visibles="allVisible.deteleOrderVisible" @closeVisible="closeVisible" />

    <!-- 导入 -->
    <el-dialog v-model="allVisible.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="importBusiness">
              <el-button type="primary" :loading="allLoading.importLoading">导入</el-button>
            </el-upload>
            <el-button @click="allVisible.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(IMPORTMOD, allText.importText)">{{ allText.importText }}</el-link></div>
          <div class="mt-4">2、填写excel文件、订单名称、客户名称、订单金额、负责人必填</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject, defineExpose } from "vue";
import { getAllListByCode, getFromValue, resetFromValue, getFirstDayOfMonth, getLastDayOfMonth, formatDate, getTemplateKey, createTaskFromType, confirmAction, downloadFile, downloadTemplate } from '@/utils/tools'
import { post, get, uploadFile } from "@/utils/request";
import { tableColumns, GETSYSFILED, GETPERSONNEL, GETGENERATEFOEM, MOD, GETTABLELIST, GETALLPRODUCT, GETTABLELISTPRODUCT, URL_OEDERUPDATE, URL_PRODUTWITHORDER, URL_DETELEITEM, EXPORTTIME, IMPORTMOD, IMPORITEM, paymentStatus } from "./api";
import { useRouter, useRoute } from "vue-router";
import { GenerateForm } from '@zmjs/form-design';
import { formatDateTime } from "@/utils/times";
import { ElTable, UploadRequestOptions } from "element-plus";
import { createTask } from "@/components/TaskModal/taskFunction";
import { tableShowOverflowTooltip } from '@/utils/globalVariables'
import { URL_FETALL } from "../customer/api";

import RelatedProducts from '@/components/relatedProducts/relatedProducts.vue'
import DeteleTables from './component/deteleTables.vue'
import TaskModal from '@/components/TaskModal/index.vue'
import personnelSearch from '@/components/translationComponent/personnelSearch/personnelSearch.vue';


const router = useRouter()
const globalPopup = inject<GlobalPopup>('globalPopup')
const filterForm = reactive<FilterForm>({ // 筛选条件 Value
  contactPerson: "",
  customerId: "",
  phoneNumber: '',
  responsibleId: '',
  createId: '',
  email: '',
  startTime: getFirstDayOfMonth(new Date()),
  endTime: formatDate(new Date())
});
const selectData = reactive({ // 下拉数据
  Personnel: [] as personnelInterface[],
  Customer: [] as any[], // 客户名称
  OrderType: [] as any[], // 订单类型
  RemittanceStatus: [{ id: 0, name: '未回款' }, { id: 1, name: '已回款' }, { id: 2, name: '已完全回款' }] as any[], // 回款状态
  AllProduct: [] as any[] // 所有产品
})
const formTablePaging = reactive({ // 分页条件
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})
const allLoading = reactive({ // 按钮加载 Loading
  formTableLading: false,
  editSaveLading: false,
  orderTemplateLoadinng: false,
  exoprtLoading: false,
  importLoading: false
})
const allVisible = reactive({
  editOrderVisible: false,
  taskModalVisible: false,
  deteleOrderVisible: false,
  importVisible: false
})
const allText = reactive({
  orderEditText: '新建订单',
  // importText: '销售订单表导出.xlsx'
  importText: '销售订单表导入.xlsx'
})
const orderTemplate = ref({
  list: [],
  config: {}
})
const filterItems = ref<FilterItem[]>([
  { label: '订单编号', key: 'orderCode', type: 'input' },
  { label: '订单名称', key: 'orderName', type: 'input' },
  { label: '客户名称', key: 'customId', type: 'select', options: selectData.Customer },
  { label: '商机名称', key: 'businessName', type: 'input' },
  { label: '订单类型', key: 'ordertype', type: 'select', options: selectData.OrderType },
  { label: '回款状态', key: 'receivedStatus', type: 'select', options: selectData.RemittanceStatus },
  { label: '负责人', key: 'inchargerId', type: 'select', options: selectData.Personnel },
  { label: '下单时间', key: '', type: 'date' },
]) // 渲染筛选条件
const orderTemplateValue = ref<any>({})
const orderTemplateKey = ref(1)
const orderTemplateRef = ref<typeof GenerateForm>()
const relatedProductsRef = ref<typeof RelatedProducts>()
const otherTableRef = ref<InstanceType<typeof ElTable>>()
const taskLoading = ref<saveLoadingType>('1')
const batchTableData = ref([])
const formTable = ref([]) // 表格数据
const productTableList = ref([])
const productTableListValue = ref([])
const taskModalForm = ref({})

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

function exportOrderTableList() {
  allLoading.exoprtLoading = true
  let valueForm = getFromValue(filterForm)
  post(EXPORTTIME, {...valueForm}).then((res) => {
    downloadFile(res.data, allText.importText)
  }).finally(() => {
    allLoading.exoprtLoading = false
  })
}

function batchDeteleItem() {
  const value = batchTableData.value.map((item: any) => item.id).join(',')
  const label = batchTableData.value.map((item: any) => item.orderName).join(',')
  orderDeteleItem(value, label, true)
}

function orderDeteleItem(value: string | number, label: string, batch: boolean = false) {
  confirmAction(`确定${batch ? '批量' : ''}删除【${label}】销售订单吗？`).then(() => {
    post(URL_DETELEITEM, { ids: value }).then(res => {
      if (res.code != 'ok') {
        globalPopup?.showError(res.msg)
        return
      }
      globalPopup?.showSuccess('删除成功')
      changeBatch(false)
      getTableList()
    }).catch((err) => {
      globalPopup?.showError(err.msg)
    })
  })
}

function submitForm(submitData: any, isClose: boolean) {
  taskLoading.value = '2'
  createTask(submitData, isClose).then((res) => {
    const { saveLoading, isClose } = res
    taskLoading.value = saveLoading
    allVisible.taskModalVisible = isClose
    globalPopup?.showSuccess('新增成功')
  }).catch((err) => {
    const { saveLoading, isClose, message } = err
    taskLoading.value = saveLoading
    allVisible.taskModalVisible = isClose
    globalPopup?.showError(message)
  })
}

function newTask(item: any) {
  const { id } = item
  taskModalForm.value = { ...createTaskFromType(2), orderId: id, }
  allVisible.taskModalVisible = true
}

function saveOrder(flag: boolean) {
  orderTemplateRef.value?.getData().then((res: any) => {
    let productTableListData = relatedProductsRef?.value?.returnData()
    for (var i in productTableListData) {
      productTableListData[i].sealPrice = productTableListData[i].sellingPrice,
        productTableListData[i].discount = productTableListData[i].discount,
        productTableListData[i].num = productTableListData[i].quantity
    }
    const produt = productTableListData ? JSON.stringify(productTableListData) : []
    const formVal = {
      ...orderTemplateValue.value,
      ...res,
      orderEndDate: res.orderEndDate ? formatDate(res.orderEndDate) : '',
      orderStartDate: res.orderStartDate ? formatDate(res.orderStartDate) : '',
      placeTime: res.placeTime ? formatDate(res.placeTime) : '',
      orderProductDetailString: produt
    }
    console.log((formVal.price || 0), (formVal.receivedPayment || 0), (formVal.price || 0) < (formVal.receivedPayment || 0))
    if((formVal.price || 0) < (formVal.receivedPayment || 0)) {
      globalPopup?.showError('已回款金额不能大于订单金额')
      return
    }
    allLoading.editSaveLading = true
    post(URL_OEDERUPDATE, formVal).then((_res) => {
      allVisible.editOrderVisible = flag
      globalPopup?.showSuccess('保存成功')
      if (flag) {
        orderTemplateRef.value?.reset()
      }
      getTableList()
    }).finally(() => {
      allLoading.editSaveLading = false
    })
  }).catch((_err: any) => {
    globalPopup?.showError('请填写完整')
  })
}

function editOrder(item: any) {
  showVisible('editOrderVisible')
  allLoading.orderTemplateLoadinng = true
  if (item) {
    editProduct(item)
    const templateKey = getTemplateKey(orderTemplate.value.list)
    let formVal: templateKey = { id: item.id }
    for (let i = 0; i < templateKey.length; i++) {
      const key = templateKey[i]
      formVal[key] = item[key]
    }
    orderTemplateValue.value = formVal
    console.log(formVal, '<============ 数据')
    allText.orderEditText = '编辑订单'
  }
  if (!item) {
    orderTemplateValue.value = {}
    productTableListValue.value = []
    allText.orderEditText = '新增订单'
  }
  setTimeout(() => {
    orderTemplateRef.value && orderTemplateRef.value.reset()
    orderTemplateKey.value++
    allLoading.orderTemplateLoadinng = false
  }, 1000)
}

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

function getTableList() {
  const formValue = getFromValue(filterForm)
  const formPaging = { pageIndex: formTablePaging.pageIndex, pageSize: formTablePaging.pageSize }
  allLoading.formTableLading = true
  post(GETTABLELIST, { ...formValue, ...formPaging }).then(res => {
    const { total, record } = res.data
    formTable.value = (record || []).map((item: any) => {
      let val = paymentStatus.find((items: any) => items.value == item.status)
      return {
        ...item,
        statusValue: val ? val.label : ''
      }
    })
    formTablePaging.total = total
  }).finally(() => {
    allLoading.formTableLading = false
  })
}

function resetFilterForm() {
  let newFilterForm = resetFromValue(filterForm, { startTime: getFirstDayOfMonth(new Date()), endTime: formatDate(new Date()) })
  Object.assign(filterForm, newFilterForm)
  getTableList()
}

function getAllProduct() {
  get(GETALLPRODUCT, { pageIndex: -1, pageSize: -1 }).then((res) => {
    const { record } = res.data
    selectData.AllProduct = record
  })
}

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(selectData)) {
      if (systemField[i] == key) {
        Object.assign(selectData, { [key]: data })
      }
    }
  }

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

  const { data: customerData } = await post(URL_FETALL, {})
  selectData.Customer = (customerData || []).map((item: any) => {
    const { id, customName } = item
    return { id, name: customName }
  })
  const res = await get(GETGENERATEFOEM)
  orderTemplate.value = JSON.parse(res.data[0].config)

  setFilterItems()
}

function changeBatch(flag: boolean = true) {
  if (flag) {
    batchTableData.value = otherTableRef.value && otherTableRef.value.getSelectionRows()
  } else {
    batchTableData.value = []
    otherTableRef.value && otherTableRef.value.clearSelection()
  }
}

function showVisible(type: keyof typeof allVisible) { // 显示弹窗
  allVisible[type] = true
}

function closeVisible(type: keyof typeof allVisible) {
  allVisible[type] = false
}

function setFilterItems() {
  filterItems.value = [
    { label: '订单编号', key: 'orderCode', type: 'input' },
    { label: '订单名称', key: 'orderName', type: 'input' },
    { label: '客户名称', key: 'customId', type: 'select', options: selectData.Customer },
    { label: '商机名称', key: 'businessName', type: 'input' },
    { label: '订单类型', key: 'orderType', type: 'select', options: selectData.OrderType },
    { label: '回款状态', key: 'receivedStatus', type: 'select', options: selectData.RemittanceStatus },
    { label: '负责人', key: 'inchargerId', type: 'select', options: selectData.Personnel },
    { label: '下单时间', key: '', type: 'date' },
  ]
}

function editProduct(row: any) {
  post(URL_PRODUTWITHORDER, { id: row.id }).then(({ data }) => {
    const list = data.map((item: any) => {
      const { id, productName, productCode, unit, unitName, typeName, type, price, inventory, orderProductDetail } = item
      return {
        id, productId: id, productName, productCode, unit, unitName, typeName, type, price, inventory,
        quantity: +orderProductDetail?.num,
        discount: +orderProductDetail?.discount,
        sellingPrice: +orderProductDetail?.sealPrice,
        totalPrice: +orderProductDetail?.totalPrice
      }
    })
    productTableListValue.value = list
  })
}

function getProductTableList() {
  post(GETTABLELISTPRODUCT, { pageIndex: -1, pageSize: -1 }).then((res) => {
    if (res.code == 'ok') {
      const { record, total } = res.data
      productTableList.value = record.map((item: any) => {
        const { id, productName, productCode, unit, unitName, typeName, type, price, inventory } = item
        return {
          id,
          productId: id,
          productName,
          productCode,
          unit,
          unitName,
          price,
          type,
          typeName,
          inventory,
          quantity: '',
          discount: '',
          totalPrice: ''
        }
      })
    }
  })
}

function handleSizeChange(val: number) {
  formTablePaging.pageIndex = 1
  formTablePaging.pageSize = val
  getTableList()
}

function handleCurrentChange(val: number) {
  formTablePaging.pageIndex = val
  getTableList()
}

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

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