<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="filterCriteriaForm" label-width="70px" style="max-width: 600px">
            <el-form-item label="线索名称">
              <el-input v-model="filterCriteriaForm.clueName" clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="线索来源">
              <el-select v-model="filterCriteriaForm.clueSourceId" placeholder="请选择" clearable>
                <el-option v-for="item in fixedData.ClueSources" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="电话号码">
              <el-input v-model="filterCriteriaForm.phone" clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="filterCriteriaForm.email" clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="客户行业">
              <el-select v-model="filterCriteriaForm.customerIndustryId" placeholder="请选择">
                <el-option v-for="item in fixedData.CustomIndustry" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户级别">
              <el-select v-model="filterCriteriaForm.customerLevelId" placeholder="请选择">
                <el-option v-for="item in fixedData.CustomLevel" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="负责人">
              <el-select v-model="filterCriteriaForm.inchargerId" 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="filterCriteriaForm.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="filterCriteriaForm.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="resetTable()">重置</El-Button>
          <El-button type="primary" class="w-full" @click="searchTable()">搜索</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="editClue(false)">新建线索</el-button>
          <el-button type="primary" @click="batchTransfer()">批量转移</el-button>
          <el-button type="primary" @click="batchDeletes()">批量删除</el-button>
          <el-button type="primary" @click="showDeteleClue(true)">回收站</el-button>
          <el-button type="primary">导入</el-button>
          <el-button type="primary">导出</el-button>
        </div>
        <div class="flex-1 w-full overflow-hidden">
          <el-table ref="clueTableRef" :data="clueTable" border v-loading="allLoading.clueTableLading"
            style="width: 100%;height: 100%;">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="clueName" label="线索名称" width="180">
              <template #default="scope">
                <el-button link type="primary" size="large" @click.prevent="toClueTableDetail(scope.row)">{{
                  scope.row.clueName
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="clueSourceValue" label="线索来源" width="180"></el-table-column>
            <el-table-column prop="phone" label="电话号码" width="180"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
            <el-table-column prop="customerIndustryValue" label="客户行业" width="180"></el-table-column>
            <el-table-column prop="customerLevelValue" label="客户级别" width="180"></el-table-column>
            <el-table-column prop="inchargerName" label="负责人" width="190"></el-table-column>
            <el-table-column prop="createName" 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="editClue(scope.row)">编辑</el-button>
                <el-button link type="primary" size="large"
                  @click="dialogVisible.taskModalVisible = true">新建任务</el-button>
                <el-button link type="danger" size="large" @click.prevent="deleteRow(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="filterCriteriaForm.pageFrom"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" :total="clueTotalTable"
            :hide-on-single-page="true" />
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible.editClueDialogVisible" 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="saveEditClue(true)">保存并新建</el-button>
            <el-button type="primary" @click="saveEditClue(false)">保存</el-button>
            <el-button @click="dialogVisible.editClueDialogVisible = 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="clueTemplate" :value="editForm" :key="generateFormKey" />
        </div>
      </div>
    </el-dialog>

    <el-dialog v-model="dialogVisible.clueDialogVisible" width="600" :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.clueText }}</h4>
          <div>
            <el-button type="primary" v-loading="allLoading.clueLoading" @click="transferClues()">转移</el-button>
            <el-button @click="dialogVisible.clueDialogVisible = false">取消</el-button>
          </div>
        </div>
      </template>
      <div class="scroll-bar m-6">
        <div class="flex mb-4">
          <div class="w-20 flex items-center justify-end pr-4">转移至:</div>
          <el-select v-model="transferForm.transferValue" placeholder="请选择" class="flex1">
            <el-option v-for="item in fixedData.Personnel" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </div>
        <div class="pl-3 text-[#e94a4a]">转移后，将看不到此线索</div>
      </div>
    </el-dialog>

    <DeteleTables :visibles="dialogVisible.deteleClueDialogVisible" @showDeteleClue="showDeteleClue" />

    <TaskModal :visible="dialogVisible.taskModalVisible" :edit-form="createTaskFromType(3)" :save-loading="'1'"
      @close="closeTaskModal" @submit="submitForm" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from "vue";
import { GETSYSFILED, MOD, GETPERSONNEL, GETTABLE, GETTEMPLATE, GETDETAIL, UNDATECLAIM, UNDATEFORM, DELTEROW } from './constant'
import { getAllListByCode, getFromValue, resetFromValue, getFirstDayOfMonth, getLastDayOfMonth, formatDate, createTaskFromType, confirmAction } from '@/utils/tools'
import { FormInstance, FormRules, ElMessageBox, ElTable } from 'element-plus'
import { post, get } from "@/utils/request";
import { useRouter, useRoute } from "vue-router";
import { GenerateForm } from '@zmjs/form-design';
import TaskModal from '@/components/TaskModal/index.vue'
import DeteleTables from "./deteleTables.vue";

// 定义类型
interface fixedDataInterface {
  id: string | number,
  companyId: string | number,
  code: string,
  name: string,
  seq: string | number,
}

interface personnelInterface {
  id: string | number,
  name: string,
  phone: string,
  jobNumber: string
}

// 定义变量
const route = useRoute()
const router = useRouter()
const globalPopup = inject<GlobalPopup>('globalPopup')
const filterCriteriaForm = reactive<filterCriteriaFormType>({ // 筛选条件form
  clueName: '',
  clueSourceId: '',
  phone: '',
  email: '',
  customerIndustryId: '',
  customerLevelId: '',
  inchargerId: '',
  startTime: getFirstDayOfMonth(new Date()),
  endTime: formatDate(new Date()),
  pageIndex: 1,
  pageFrom: 10
})
const generateFormKey = ref(1)
const allLoading = reactive({
  clueTableLading: false,
  generateFormLading: false,
  clueLoading: false,
})
const dialogVisible = reactive({
  editClueDialogVisible: false,
  taskModalVisible: false,
  clueDialogVisible: false,
  deteleClueDialogVisible: false
})
const allText = reactive({
  editClueText: '新建线索',
  clueText: '转移线索'
})
const fixedData = reactive({
  ClueSources: [] as fixedDataInterface[],
  CustomIndustry: [] as fixedDataInterface[],
  CustomLevel: [] as fixedDataInterface[],
  Personnel: [] as personnelInterface[]
})
const clueTable = ref([]) // 线索table数据
const clueTotalTable = ref(0) // 线索 table 数据总数
const clueTableRef = ref<InstanceType<typeof ElTable>>() // 线索table dom
const generateForm: any = ref(null) // 模板
const clueTemplate = ref({
  list: [],
  config: {}
}) // 线索模板
const editForm = ref({}) // 编辑表单

// 批量变量
const transferForm = reactive({
  transferValue: '',
  batchTransferIds: '',
})


// 定义方法
function showDeteleClue(flag: boolean) {
  dialogVisible.deteleClueDialogVisible = flag
}

function transferClues() {
  const { transferValue, batchTransferIds } = transferForm
  const ids = batchTransferIds
  const inchargerId = transferValue
  if (!inchargerId) {
    globalPopup?.showWarning('请选择转移的人员')
    return
  }
  post(UNDATECLAIM, { ids, inchargerId }).then((res) => {
    if (res.code == 'ok') {
      globalPopup?.showSuccess('批量转移成功')
      dialogVisible.clueDialogVisible = false
      getClueTable()
    }
  })
}

function searchTable() {
  getClueTable()
}

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

function closeTaskModal() {
  dialogVisible.taskModalVisible = false
}

function submitForm(submitData: any, isClose: boolean) {
  console.log(submitData, isClose)
}

function editClue(item: any) {
  dialogVisible.editClueDialogVisible = true
  allLoading.generateFormLading = true
  setTimeout(() => {
    generateForm.value && generateForm.value.reset()
    generateFormKey.value++
    allLoading.generateFormLading = false
  }, 1000);
  if (!item) {
    allText.editClueText = '新建线索'
    editForm.value = {}
    return
  }
  editForm.value = JSON.parse(JSON.stringify(item))
  allText.editClueText = '编辑线索'
}

async function saveEditClue(flag: boolean) {
  const data = await generateForm.value.getData()
  let newData = { ...editForm.value, ...data }
  delete newData.createTime
  post(UNDATEFORM, { ...newData }).then((res) => {
    if (res.code != 'ok') {
      globalPopup?.showError(res.msg)
      return
    }
    globalPopup?.showSuccess('保存成功')
    if (!flag) {
      editForm.value = {}
      generateForm.value && generateForm.value.reset()
      generateFormKey.value++
    }
    dialogVisible.editClueDialogVisible = flag
    getClueTable()
  }).catch((_err) => {
    console.log(_err)
  })
}

function deleteRow(row: any) {
  confirmAction(`确定删除【${row.clueName}】线索吗？`).then(() => {
    post(DELTEROW, { ids: row.id }).then(res => {
      if (res.code != 'ok') {
        globalPopup?.showError(res.msg)
        return
      }
      globalPopup?.showSuccess('删除成功')
      getClueTable()
    })
  })
}

function batchTransfer() {
  const data = clueTableRef.value && clueTableRef.value.getSelectionRows()
  if (!data.length) {
    globalPopup?.showWarning('请选择数据')
    return
  }
  transferForm.batchTransferIds = data.map((item: any) => item.id).join(',')
  dialogVisible.clueDialogVisible = true
}

function batchDeletes() {
  const data = clueTableRef.value && clueTableRef.value.getSelectionRows()
  if (!data.length) {
    globalPopup?.showWarning('请选择数据')
    return
  }
  const str = data.map((item: any) => item.clueName).join(',')
  const ids = data.map((item: any) => item.id).join(',')

  confirmAction(`确定批量删除这些【${str}】线索吗？`, '', 'warning').then(() => {
    post(DELTEROW, { ids }).then(res => {
      if (res.code != 'ok') {
        globalPopup?.showError(res.msg)
        return
      }
      globalPopup?.showSuccess('删除成功')
      getClueTable()
    })
  })
}

function toClueTableDetail(row: any) {
  console.log('点击跳转详情')
  router.push({
    path: `${MOD}/detail`,
    query: { id: row.id }
  })
}

function getClueTable() {
  allLoading.clueTableLading = true
  let valueForm = getFromValue(filterCriteriaForm)
  post(GETTABLE, { ...valueForm }).then((res: any) => {
    let { data } = res
    for (let i in data.data) {
      data.data[i].createTime = formatDate(new Date(data.data[i].createTime))
    }
    clueTable.value = data.data
    clueTotalTable.value = data.total
    allLoading.clueTableLading = false
  }).catch((_error) => {
    allLoading.clueTableLading = false
  })
}

function handleSizeChange(val: number) {
  filterCriteriaForm.pageIndex = 1
  filterCriteriaForm.pageFrom = val
  getClueTable()
}

function handleCurrentChange(val: number) {
  filterCriteriaForm.pageIndex = val
  getClueTable()
}

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)
  clueTemplate.value = JSON.parse(res.data[0].config)
}

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

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