<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">
            <el-form-item v-for="(item, index) in filterItems" :key="index" :label="item.label">
              <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>
          </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="resetForm()" :loading="allLoading.formTableLading">重置</El-Button>
          <El-button type="primary" class="w-full" :loading="allLoading.formTableLading"
            @click="getContactPerson()">搜索</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> -->
          <el-button type="primary" v-permission="['contactsAdd']" @click="editContacts(false)">新建联系人</el-button>
          <el-button type="primary" @click="batchDeteleItem" :disabled="batchTableData.length <= 0">批量删除</el-button>
          <el-button type="primary" @click="showVisible('deteleContactsVisible')">回收站</el-button>
          <el-button type="primary" v-permission="['contactsImport']" @click="showVisible('importVisible')">导入</el-button>
          <el-button type="primary" v-permission="['contactsExport']" @click="exportCustomerTableList()" :loading="allLoading.exoprtLoading">导出</el-button>
        </div>
        <div class="flex-1 w-full overflow-hidden">
          <!-- 表格 -->
          <el-table ref="contactsTableRef" :data="formTable" 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.name
                  }}</el-button>
                </template>
                <template v-if="column.event === 'getSex'">
                  {{ getSex(scope.row.sex) }}
                </template>
              </template>
            </el-table-column>
            <el-table-column :label="'操作'" :width="'200px'" fixed="right" v-permission="['contactsEdit', 'tasksAdd']">
              <template #default="scope">
                <el-button link type="primary" size="large" v-permission="['contactsEdit']" @click="editContacts(scope.row)">编辑</el-button>
                <el-button link type="primary" size="large" v-permission="['tasksAdd']" @click="newTask(scope.row)">新建任务</el-button>
                <el-button link type="danger" size="large" v-permission="['contactsEdit']"
                  @click="contactsDeteleItem(scope.row.id, scope.row.customName)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="flex justify-end pt-3">
          <!-- 分页 -->
          <el-pagination layout="total, prev, pager, next, sizes" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :total="tableTotal" :hide-on-single-page="true" />
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="allVisible.editContactsVisible" 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.editContactsText }}</h4>
          <div>
            <el-button type="primary" :loading="allLoading.editContactsSaveLoading" v-if="!contactsTemplateValue.id"
              @click="editContactsSave(true)">保存并新建</el-button>
            <el-button type="primary" :loading="allLoading.editContactsSaveLoading"
              @click="editContactsSave(false)">保存</el-button>
            <el-button @click="closeVisible('editContactsVisible')">取消</el-button>
          </div>
        </div>
      </template>
      <div class="h-[60vh] overflow-y-auto scroll-bar pt-3">
        <div class="ml-4 mr-4">
          <GenerateForm ref="contactsTemplateRef" :data="contactsTemplate" :value="contactsTemplateValue"
            :key="contactsTemplateRefKey" v-loading="allLoading.contactsTemplateRefLoading" />
        </div>
      </div>
    </el-dialog>

    <!-- 回收站 -->
    <DeteleTables :visibles="allVisible.deteleContactsVisible" @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>

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

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from "vue";
import { getAllListByCode, getFromValue, resetFromValue, getTemplateKey, confirmAction, downloadTemplate, downloadFile, createTaskFromType } from '@/utils/tools'
import { post, get, uploadFile } from "@/utils/request";
import { actionButtons, tableColumns, GETSYSFILED, GETPERSONNEL, GETGENERATEFOEM, MOD, URL_PAGECONTACTS, getSex, URL_ADD, URL_UPLOAD, URL_BATCHDETELE, URL_DETELERECYCLE, IMPORTMOD, URL_IMPORTDATACONTACTS, URL_EXPORTDATACONTACTS } from "./api";
import { useRouter, useRoute } from "vue-router";
import { GenerateForm } from '@zmjs/form-design';
import { URL_FETALL } from "../customer/api";
import { ElTable, UploadRequestOptions } from "element-plus";

import DeteleTables from './component/deteleTables.vue'
import TaskModal from '@/components/TaskModal/index.vue'
import { createTask } from "@/components/TaskModal/taskFunction";

const router = useRouter()
const globalPopup = inject<GlobalPopup>('globalPopup')

const filterForm = reactive<FilterForm>({ // 筛选条件
  contactPerson: "",
  customerId: "",
  phoneNumber: '',
  responsibleId: '',
  createId: '',
  email: '',
});
const formTablePaging = reactive({ // 分页条件
  pageIndex: 1,
  pageSize: 10,
})
const tableTotal = ref(0)
const selectData = reactive({ // 下拉数据
  Personnel: [] as personnelInterface[],
  Customer: [] as any[],
})
const filterItems = ref<FilterItem[]>([
  { label: '联系人', key: 'contactPerson', type: 'input' },
  { label: '客户名称', key: 'customerId', type: 'select', options: selectData.Customer },
  { label: '电话号码', key: 'phoneNumber', type: 'input' },
  { label: '邮箱', key: 'email', type: 'input' },
  { label: '负责人', key: 'responsibleId', type: 'select', options: selectData.Personnel },
  { label: '创建人', key: 'createId', type: 'select', options: selectData.Personnel },
])
const contactsTemplate = ref({
  list: [],
  config: {}
})
const contactsTemplateValue = ref<any>({})
const contactsTemplateRefKey = ref(1)
const contactsTemplateRef = ref<typeof GenerateForm>()
const contactsTableRef = ref<InstanceType<typeof ElTable>>()
const formTable = ref([]) // 表格数据
const batchTableData = ref([])
const taskModalForm = ref({})
const taskLoading = ref<saveLoadingType>('1')
const allLoading = reactive({ // 按钮加载 Loading
  formTableLading: false,
  editContactsSaveLoading: false,
  contactsTemplateRefLoading: false,
  importLoading: false,
  exoprtLoading: false
})
const allVisible = reactive({
  editContactsVisible: false,
  taskModalVisible: false,
  deteleContactsVisible: false,
  importVisible: false
})
const allText = reactive({
  editContactsText: '新建联系人',
  importText: '联系人导入模板.xlsx',
  exportText: '联系人导出.xlsx'
})

// 方法
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(0), contactsId: id, }
  showVisible('taskModalVisible')
}

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

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

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

function contactsDeteleItem(value: string | number, label: string, batch: boolean = false) {
  confirmAction(`确定${batch ? '批量' : ''}删除【${label}】联系人吗？`).then(() => {
    // let url = batch ? URL_BATCHDETELE : URL_DETELERECYCLE
    let url = URL_DETELERECYCLE
    post(url, { ids: value }).then(res => {
      if (res.code != 'ok') {
        globalPopup?.showError(res.msg)
        return
      }
      globalPopup?.showSuccess('删除成功')
      changeBatch(false)
      getContactPerson()
    }).catch((err) => {
      globalPopup?.showError(err.msg)
    })
  })
}

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


function editContactsSave(flag: boolean) {
  contactsTemplateRef.value?.getData().then((res: any) => {
    allLoading.editContactsSaveLoading = true
    let url = allText.editContactsText == '新建联系人' ? URL_ADD : URL_UPLOAD
    post(url, { ...contactsTemplateValue.value, ...res }).then((_res) => {
      allVisible.editContactsVisible = flag
      globalPopup?.showSuccess('保存成功')
      if (flag) {
        contactsTemplateRef.value?.reset()
        allText.editContactsText = '新建联系人'
      }
      getContactPerson()
    }).finally(() => {
      allLoading.editContactsSaveLoading = false
    })
  }).catch((_err: any) => {
    console.log(_err)
    globalPopup?.showError('请填写完整')
  })
}

function editContacts(row: any) { // row 有数据代表编辑
  showVisible('editContactsVisible')
  if (row) {
    const templateKey = getTemplateKey(contactsTemplate.value.list)
    const formVal: templateKey = { id: row.id }
    for (let i in templateKey) {
      if(row[templateKey[i]]) {
        formVal[templateKey[i]] = templateKey[i] == 'sex' ? row[templateKey[i]] + '' : row[templateKey[i]]
      }
    }
    setTemplateVal(formVal)
    allText.editContactsText = '编辑联系人'
  } else {
    setTemplateVal()
    allText.editContactsText = '新建联系人'
  }
}

function setTemplateVal(val: any = {}) {
  console.log(val)
  contactsTemplateValue.value = val
  allLoading.contactsTemplateRefLoading = true
  setTimeout(() => {
    contactsTemplateRefKey.value++
    allLoading.contactsTemplateRefLoading = false
  }, 1000);
}

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

function getContactPerson() {
  allLoading.formTableLading = true
  const formVal = getFromValue(filterForm)
  post(URL_PAGECONTACTS, { ...formVal, ...formTablePaging }).then((res) => {
    const { records, total } = res.data
    formTable.value = records
    tableTotal.value = total
  }).finally(() => {
    allLoading.formTableLading = false
  })
}

function resetForm() {
  let newResetForm = resetFromValue(filterForm)
  Object.assign(filterForm, newResetForm)
  getContactPerson()
}

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

  const res = await get(URL_FETALL, {})
  selectData.Customer = (res.data || []).map((item: any) => {
    const { id, customName } = item
    return {
      id,
      name: customName
    }
  })

  const datas = await get(GETGENERATEFOEM)
  contactsTemplate.value = JSON.parse(datas.data[0].config)

  setFilterItems()
}

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

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

function showVisible(type: keyof typeof allVisible) {
  allVisible[type] = true
}

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

function setFilterItems() {
  console.log(selectData)
  filterItems.value = [
    { label: '联系人', key: 'contactPerson', type: 'input' },
    { label: '客户名称', key: 'customerId', type: 'select', options: selectData.Customer },
    { label: '电话号码', key: 'phoneNumber', type: 'input' },
    { label: '邮箱', key: 'email', type: 'input' },
    { label: '负责人', key: 'responsibleId', type: 'select', options: selectData.Personnel },
    { label: '创建人', key: 'createId', type: 'select', options: selectData.Personnel },
  ]
}

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

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