<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>
                <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 v-for="(button, index) in actionButtons" :key="index" type="primary">{{ button.text }}</el-button>
        </div>
        <div class="flex-1 w-full overflow-hidden">
          <!-- 表格 -->
          <el-table ref="otherTableRef" :data="formTable" border v-loading="allLoading.formTableLading"
            style="width: 100%;height: 100%;">
            <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>
                </template>
              </template>
            </el-table-column>
            <el-table-column :label="'操作'" :width="'200px'" fixed="right">
              <template #default="scope">
                <el-button link type="primary" size="large">编辑</el-button>
                <el-button link type="primary" size="large">新建任务</el-button>
                <el-button link type="danger" size="large">删除</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" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from "vue";
import { getAllListByCode, getFromValue, resetFromValue, getFirstDayOfMonth, getLastDayOfMonth, formatDate } from '@/utils/tools'
import { post, get } from "@/utils/request";
import { actionButtons, tableColumns, GETSYSFILED, GETPERSONNEL, GETGENERATEFOEM, MOD, GETTABLELIST, GETALLPRODUCT } from "./api";
import { useRouter, useRoute } from "vue-router";
import { URL_FETALL } from "../customer/api";

const router = useRouter()

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 filterItems = ref<FilterItem[]>([]) // 渲染筛选条件
const formTablePaging = reactive({ // 分页条件
  currentPage: 1,
  pageSize: 10,
  total: 0,
})
const generateFormData = ref([]) // 自定义表单数据

const formTable = ref([]) // 表格数据
const allLoading = reactive({ // 按钮加载 Loading
  formTableLading: false,
})
const allVisible = reactive({

})

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

function getTableList() {
  const formValue = getFromValue(filterForm)
  const formPaging = { pageIndex: formTablePaging.currentPage, pageSize: formTablePaging.pageSize }
  allLoading.formTableLading = true
  post(GETTABLELIST, { ...formValue, ...formPaging }).then(res => {
    const { total, record } = res.data
    formTable.value = record
    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)
  // generateFormData.value = JSON.parse(res.data[0].config)

  setFilterItems()
}

function setFilterItems() {
  filterItems.value = [
    { label: '订单编号', key: 'orderCode', type: 'input' },
    { label: '订单名称', key: 'orderName', type: 'input' },
    { label: '客户名称', key: 'customId', type: 'select', options: selectData.Customer },
    { label: '商机名称', key: 'businessOpportunityId', 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' },
  ]
}

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

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