<template>
  <div class="card-search">
    <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form" :model="searchParams">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="任务名称" :label-col="{span:6}" name="name">
            <a-input v-model:value="searchParams.name" placeholder=""/>
          </a-form-item>
        </a-col>
        <a-col  :span="6">
          <a-form-item label="下达时间" :label-col="{span:6}" name="name">
            <a-range-picker format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" @change="onRangeChange"/>
          </a-form-item>
        </a-col>
        <a-col  :span="6">
          <a-form-item label="完成时间" :label-col="{span:6}" name="name">
            <a-range-picker format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']" @change="onFinishChange"/>
          </a-form-item>
        </a-col>
        <a-col :span="5" style="text-align: right">
          <a-button type="primary" html-type="submit" @click="onSearch">查询</a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="6">
          <a-form-item label="所属县区" :label-col="{span:6}" name="regionCode">
            <a-select
              ref="select"
              v-model:value="searchParams.regionCode"
              :options="regionList"
              :field-names="{ label: 'name', value: 'code' }"
              :allow-clear="true"
              @change="changeCity"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="所属街道" :label-col="{span:6}" name="streetCode">
            <a-select
              ref="select"
              v-model:value="searchParams.streetCode"
              :options="streetList"
              :field-names="{ label: 'name', value: 'code' }"
              :allow-clear="true"
              @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="任务类型" :label-col="{span:6}" name="workTypeId">
            <a-select
              ref="select"
              v-model:value="searchParams.workTypeId"
              :options="taskTypeList"
              :field-names="{ label: 'name', value: 'value' }"
              :allow-clear="true"
              @change="loadData"
            >
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="edit-operation">
        <a-col :span="24" style="text-align: right">
          <a-button type="primary" html-type="submit" @click='onAdd'>新增</a-button>
          <a-button type="primary" html-type="submit" @click='exportPost()'>导出</a-button>
        </a-col>
      </a-row>
    </a-form>
    <div class="search-result-list">
      <a-table :columns="columns" :data-source="dataList" :scroll="{ x:'100%', y: 500 }" :pagination="pagination"
               :loading="formState.loading"
               @change="handleTableChange"
               :row-selection="{ selectedRowKeys: formState.selectedRowKeys, onChange: onSelectChange}"
               :row-key="(record)=>record.dotaskID"
               bordered>
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'operation'">
            <div class="table-operation">
              <a-button type="link" size="small" @click='onOperates(record.institutionID,"修改",false)'>编辑</a-button>
              <a-button type="link" size="small" @click="onDel(record)">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts">
import {get} from '@/api/common';
import {reactive, ref, computed, defineComponent} from 'vue';
import {DownOutlined, UpOutlined} from '@ant-design/icons-vue';
import type {FormInstance,SelectProps} from 'ant-design-vue';
import type {TableColumnsType, TableProps} from 'ant-design-vue';
import {getList} from '@/api/taskAndLog/dotask';
import BExportExcel from "@/components/basic/excel/exportExcel/exportExcel.vue";
import {getPaginationTotalTitle} from "@/utils/common";
import {message} from "ant-design-vue";
import dayjs from 'dayjs';
import {useTabsViewStore} from "@/store/modules/tabsView";

export default defineComponent({
  name: 'doTaskList',
  components: { DownOutlined, UpOutlined, BExportExcel},
  setup() {
    const formRef = ref<FormInstance>();
    const searchParams = reactive({
      pageIndex: 1,
      pageSize: 20,
      primaryKey: '',
      recordStatus:1,
      startTime:'',
      endTime:'',
      finishStartTime:'',
      finishEndTime:'',
      workTypeId:'',
      regionCode:'',
      streetCode:''
    });
    const formState = reactive({
      total: 0,
      selectedRowKeys: [],
      loading: false
    });
    const columns: TableColumnsType = [
      {
        title: '序号',
        align: "center",
        key: 'institutionID',
        customRender: item => `${searchParams.pageSize * (searchParams.pageIndex - 1) + item.index + 1}`
      },
      {title: '任务名称', dataIndex: 'dotaskName', key: 'dotaskName', align: "center"},
      {title: '任务类型', dataIndex: 'workTypeName', key: 'workTypeName', width: 120, align: "center"},
      {
        title: '任务完成时间', dataIndex: 'finishTime', key: 'finishTime', align: "center", customRender: (item) => {
          return item.record.finishTime==null?"": (dayjs(item.record.finishTime).format('YYYY-MM-DD'))
        }
      },
      {title: '所属县区', dataIndex: 'regionName', key: 'regionName', align: "center"},
      {title: '所属街道', dataIndex: 'streetName', key: 'streetName', align: "center"},
      {title: '执行用户数', dataIndex: 'userCount', key: 'userCount', align: "center"},
      {title: '下达时间', dataIndex: 'createTime', key: 'createTime', align: "center",customRender:(item)=>{
          return item.record.createTime==null?"": (dayjs(item.record.createTime).format('YYYY-MM-DD'))
        }},
      {title: '下达人', dataIndex: 'createName', key: 'createName', align: "center"},
      {title: '操作', key: 'operation', fixed: 'right', width: 170, align: "center"},
    ];
    const pagination = computed(() => ({
      total: formState.total,
      current: searchParams.pageIndex,
      pageSize: searchParams.pageSize,
      showSizeChanger: true,
      showTotal: total => getPaginationTotalTitle(total)
    }));

    const tabsViewStore = useTabsViewStore();
    const regionList = ref<SelectProps['options']>();
    const streetList = ref<SelectProps['options']>();
    const taskTypeList = ref<SelectProps['options']>();
    const dataList = ref([]);

    const onAdd = () => {
      tabsViewStore.addTabByPath('/taskAndLog/dotask/add', null);
    };
    const onEdit = (item: any) => {
      tabsViewStore.addTabByPath('/taskAndLog/dotask/edit', { id: item.dotaskID });
    };

    get('system/area/getCityList',{}).then(data=>{
      console.log(data);
      regionList.value=data;
      console.log(regionList.value);
    });

    get('system/dictionary/getDictionaryItemByCodeList',{code:'TaskType'}).then(data=>{
      console.log(data);
      taskTypeList.value=data;
    });

    const changeCity=()=>{
      get('system/area/getAreaList',{code:searchParams.regionCode}).then(data=>{
        console.log(data);
        streetList.value=data;
        console.log(streetList.value);
      })
      loadData();
    }

    const loadData = async function () {
      formState.loading = true;
      const result: any = await getList(searchParams);
      dataList.value = result.list;
      console.log(dataList.value);
      formState.total = result.total;
      formState.loading = false;
    }

    const handleTableChange: TableProps['onChange'] = (pag: { pageSize: number; current: number },) => {
      searchParams.pageIndex = pag.current;
      searchParams.pageSize = pag.pageSize;
      loadData();
    };

    const onSelectChange = (selectedRowKeys: any) => {
      formState.selectedRowKeys = selectedRowKeys;
    };

    const onRangeChange=(dateString)=>{
      searchParams.startTime = dateString ? dateString[0].format("YYYY-MM-DD") : '';
      searchParams.endTime = dateString ? dateString[1].format("YYYY-MM-DD") : '';
      loadData();
    }

    const onFinishChange=(dateString)=>{
      searchParams.finishStartTime = dateString ? dateString[0].format("YYYY-MM-DD") : '';
      searchParams.finishEndTime = dateString ? dateString[1].format("YYYY-MM-DD") : '';
      loadData();
    }

    const onSearch = () => {
      loadData();
    }

    const onDel = (item: any) => {
      if (item) {
        formState.selectedRowKeys.push(item.InstitutionID as never)
      }

      if (formState.selectedRowKeys.length <= 0) {
        message.warning('请选择需要删除的数据！');
        return false;
      }

    };

    const importPost = () => {
      console.log('导入');
    }
    const exportPost = () => {
      console.log('导出');
    }
    const onOperates = () => {
      console.log('新增');
    };

    return {
      changeCity,
      regionList,
      streetList,
      taskTypeList,
      formRef,
      searchParams,
      formState,
      columns,
      pagination,
      dataList,
      handleTableChange,
      onSelectChange,
      onSearch,
      onOperates,
      importPost,
      exportPost,
      onDel,
      onRangeChange,
      onFinishChange,
      loadData,
      onAdd,
      onEdit
    };
  },
  created() {
    this.loadData();
  },
  activated() {
    if (history.state.params?.reload)
      this.loadData();
  }
});
</script>
<style lang="less" scoped></style>
