<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 scroll-bar">
          <el-form :model="searchForm">
            <el-form-item label="任务名称：" label-width="7em" prop="taskName">
              <el-input v-model="searchForm.taskName" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="优先级：" label-width="7em" prop="priority">
              <el-select v-model="searchForm.priority" placeholder="请选择">
                <el-option v-for="item in PRIORITY" :key="item.value" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="客户名称：" label-width="7em" prop="customerName">
              <el-input v-model="searchForm.customerName" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="联系人：" label-width="7em" prop="tel">
              <el-input v-model="searchForm.tel" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="执行人：" label-width="7em" prop="tel">
              <el-select v-model="searchForm.status" placeholder="请选择">
                <el-option v-for="item in STATUS" :key="item.value" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="商机名称：" label-width="7em" prop="tel">
              <el-input v-model="searchForm.tel" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="销售订单：" label-width="7em" prop="tel">
              <el-input v-model="searchForm.tel" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="线索名称：" label-width="7em" prop="tel">
              <el-input v-model="searchForm.tel" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="任务状态：" label-width="7em" prop="status">
              <el-select v-model="searchForm.status" placeholder="请选择">
                <el-option v-for="item in STATUS" :key="item.value" :value="item.value" :label="item.label" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间：" label-width="7em" prop="startDate">
              <el-date-picker v-model="searchForm.startDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="截止时间：" label-width="7em" prop="endDate">
              <el-date-picker v-model="searchForm.endDate" type="date" placeholder="选择日期" 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 size="large" class="w-full" @click="reset()">重置</el-Button>
          <el-button type="primary" size="large" class="w-full" @click="search()">搜索</el-Button>
        </div>
      </div>
    </div>
    <div class="flex-1 p-5 overflow-auto" v-loading="loading">
      <div class="bg-white w-full h-full p-3 shadow-md rounded-md flex flex-col">
        <div class="ml-auto p-3">
          <el-button type="primary" @click="createTasks()">创建任务</el-Button>
          <el-button type="primary" :loading="btnLoading" @click="deleteTasks()">批量删除</el-Button>
          <el-button type="primary" @click="openImportModal()">导入</el-Button>
          <el-button type="primary" :loading="btnLoading" @click="exportTasks()">导出</el-Button>
        </div>
        <div class="flex-1">
          <el-table :data="tableData" style="width: 100%;height: 100%;" ref="tableRef">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="taskName" label="任务名称" header-align="center" align="center" show-overflow-tooltip
              width="200" />
            <el-table-column prop="priority" label="优先级" width="90" :sortable="true" header-align="center"
              align="center">
              <template #default="scope">
                {{ PRIORITY.find(item => item.value == scope.row.priority)?.label }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" header-align="center" align="center">

              <template #default="scope">
                <el-text :type="STATUS[scope.row.status]?.type">
                  {{ STATUS[scope.row.status]?.label }}
                </el-text>
              </template>
            </el-table-column>
            <el-table-column prop="customerName" label="执行人" width="120" header-align="center" align="center" />
            <el-table-column prop="startDate" label="开始时间" width="120" :sortable="true" header-align="center"
              align="center" />
            <el-table-column prop="endDate" label="截止时间" width="120" :sortable="true" header-align="center"
              align="center" />
            <el-table-column prop="contactsName" label="联系人" header-align="center" align="center" width="120" />
            <el-table-column prop="contactsTel" label="联系人号码" header-align="center" align="center" width="140" />
            <el-table-column prop="customerName" label="客户名称" header-align="center" align="center" width="120" />
            <el-table-column prop="businessName" label="商机名称" header-align="center" align="center" width="200" />
            <el-table-column prop="businessName" label="销售订单" header-align="center" align="center" width="200" />
            <el-table-column prop="businessName" label="线索名称" header-align="center" align="center" width="200" />
            <el-table-column fixed="right" label="操作" header-align="center" align="center" width="150">

              <template #default="scope">
                <el-button link type="primary" size="small" @click.prevent="editRow(scope.row)">
                  编辑
                </el-button>
                <el-button link type="primary" size="small" v-if="scope.row.status == '3'"
                  @click.prevent="restart(scope.$index)">
                  重启
                </el-button>
                <el-button link type="primary" size="small" v-else @click.prevent="finishRow(scope.$index, scope)">
                  完成
                </el-button>

                <el-button link type="danger" size="small" @click.prevent="deleteRow(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="ml-auto">
          <el-pagination layout="total, prev, pager, next, sizes" :total="totalCount"
            :current-page="searchForm.pageIndex" hide-on-single-page @size-change="sizeChage"
            @current-change="currentChange" />
        </div>
      </div>
    </div>
    <TaskModal :visible="taskModalVisible" :save-loading="taskLoading" :edit-form="taskForm" @close="closeTaskModal"
      @submit="submitForm" />
    <ImportModal :visible="importVisible" :save-loading="importLoading" @close="closeImportModal"
      @submit="importExcel" />
    <ExportModal :visible="exportVisible" :save-loading="exportLoading" @close="closeExportModal"
      @submit="exportExcel" />
  </div>
</template>

<script lang="ts" setup>
import { inject, onBeforeMount, onMounted, ref } from 'vue';
import { useStore } from '@/store';
import { MOD, PRIORITY, STATUS, defaultSearchForm, PAGE_LIST } from './api';
import { dayjs, ElTable } from 'element-plus';
import TaskModal from '@/components/TaskModal/index.vue';
import ImportModal from './ImportModal.vue';
import ExportModal from './ExportModal.vue';
import { post, uploadFile } from '@/utils/request';
import { getFromValue } from '@/utils/tools';
const { getFunctionList } = useStore()
const globalPopup = inject<GlobalPopup>('globalPopup')
const pagePermission = ref<any[]>();
const taskModalVisible = ref(false);
const taskForm = ref<any>();
const taskLoading = ref<saveLoadingType>("1");
function closeTaskModal() {
  taskModalVisible.value = false;
  taskForm.value = null;
}
function submitForm(data: any, isClose: boolean) {
  const { executorId } = data;
  console.log("原有的数据", data, isClose);
  let params = {
    ...data
  }
  if (executorId) {
    params = {
      ...params,
      executorId: executorId.join(',')
    }
  }
  console.log("提交的数据水水水水", params, isClose);
  taskLoading.value = "2";
  setTimeout(() => {
    taskLoading.value = "3";
    taskModalVisible.value = isClose;
  }, 2000)

}
const searchForm = ref<any>();

const tableRef = ref<InstanceType<typeof ElTable>>();
const loading = ref<boolean>(false);
const totalCount = ref<number>(0);
const tableData = ref<any[]>([
  {
    taskName: '任务1111111111111111111111111',
    contactsTel: "15100111111",
    contactsName: "水水水水",
    customerName: '李四',
    status: 0,
    priority: 0,
    executorId: [1, 2], //执行人id
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: dayjs().format('YYYY-MM-DD'),
    repeat:1,
    taskType: 1,
    endType: 1,
    taskDesc: "任务秒数",
    repeatType:4,
    repeatDesignDay: "1,4,3,4",
    taskLogs: [
      {
        id: 3,
        modTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        userName: '张三',
        content: '删除任务'
      },
      {
        id: 2,
        modTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        operateType: '2',
        userName: '张三',
        content: '修改任务'
      }, {
        id: 1,
        modTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        operateType: '1',
        userName: '张三',
        content: '创建任务'
      }
    ]
  },
  {
    taskName: '任务222',
    customerName: '张三',
    status: '1',
    priority: '1',
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: dayjs().format('YYYY-MM-DD'),
    taskType: '2'
  },
  {
    taskName: '任务333',
    customerName: '王五',
    status: '2',
    priority: '2',
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: dayjs().format('YYYY-MM-DD'),
    taskType: '0'
  },
  {
    taskName: '任务444',
    customerName: '赵六',
    status: '3',
    priority: '1',
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: dayjs().format('YYYY-MM-DD'),
    taskType: '3'
  },
  {
    taskName: '任务555',
    customerName: '马六',
    status: '1',
    priority: '2',
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: dayjs().format('YYYY-MM-DD'),
  },
  {
    taskName: '任务666',
    customerName: '吴七',
    status: '3',
    priority: '0',
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: dayjs().format('YYYY-MM-DD'),
  },
  {
    taskName: '任务777',
    customerName: '钱八',
    status: '0',
    priority: '1',
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: dayjs().format('YYYY-MM-DD'),
  }
])
function search() {
  loading.value = true;
  post(PAGE_LIST, getFromValue(searchForm.value)).then(({ data }) => {
    loading.value = false;
    const { total, record } = data;
    totalCount.value = total;
    // tableData.value = record;
  }).catch(err => {
    console.log("err", err);
    loading.value = false;
  })
}
function reset() {
  searchForm.value = { ...defaultSearchForm };
}
function sizeChage(currentSize: number): void {
  console.log("object", currentSize);
  searchForm.value = {
    ...searchForm.value,
    pageSize: currentSize,
    pageIndex: 1
  }
  search()
}

function currentChange(currentPage: number): void {
  console.log("object", currentPage);
  searchForm.value = {
    ...searchForm.value,
    pageIndex: currentPage
  }
  search()
}

function createTasks() {
  taskModalVisible.value = true;
  taskForm.value = null;
}
function deleteTasks() {
  console.log("deleteTasks", searchForm.value);
  console.log(dayjs().format('YYYY-MM-DD'));
}


const importVisible = ref(false);
const importLoading = ref<saveLoadingType>("1");
function openImportModal() {
  importVisible.value = true;
}
function closeImportModal() {
  importVisible.value = false;
}
function importExcel(data: any) {
  console.log("需要提交的数据,importExcel", data);
  return
  const formData = new FormData();
  formData.append("file", data);
  formData.append("projectId", "32277");
  importLoading.value = "2";
  uploadFile("/document/uploadDocument", formData).then(_res => {
    globalPopup?.showSuccess("导入成功")
    importLoading.value = "3";
  }).catch(err => {
    globalPopup?.showError(err)
    importLoading.value = "4";
  })
}

const exportVisible = ref(false);
const exportLoading = ref<saveLoadingType>("1");
const btnLoading = ref(false);
function exportTasks() {
  const data = tableRef.value?.getSelectionRows()
  if (data.length === 0) {
    // TODO 
    exportVisible.value = true;
    return
  }
  btnLoading.value = true;
  setTimeout(() => {
    btnLoading.value = false;
  }, 2000)
}
function closeExportModal() {
  exportVisible.value = false;
}
function exportExcel(data: any) {
  console.log("export", data);
  exportLoading.value = "2";
  setTimeout(() => {
    exportLoading.value = "3";
    exportVisible.value = false;
  }, 2000)
}
function editRow(row: any) {
  taskModalVisible.value = true;
  taskForm.value = row;
}
function finishRow(index: any, scope: any) {
  console.log("finishRow", index, scope);
}
function restart(index: any) {
  console.log("restart", index);
}
function deleteRow(index: any) {
  console.log("deleteRow", index);
}
onBeforeMount(() => {
  pagePermission.value = getFunctionList(MOD);
  searchForm.value = { ...defaultSearchForm };
})
onMounted(() => {
  search()
})
</script>

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