<template>
    <div class="task_manage_page list_page">
        <div class="list_page_content">
            <div class="list_top_content">
                <!-- <div class="list_top_search_content">
                    <div class="search_content_left">
                        <filterComponent :title="'Task Name'"><a-input v-model:value="name" size="large" placeholder="Please input Task Name or Id" @keydown.enter="searchList"/></filterComponent>

                        <filterComponent :title="'Fashion Attributes'">
                            <a-select
                                v-model:value="type"
                                size="large"
                                style="width:280px"
                                :options="taskTypeList"
                                placeholder="Please select"
                                allowClear
                                ></a-select>
                        </filterComponent>
						
                        <filterComponent :title="'Date'"><a-range-picker v-model:value="addTime" size="large" :placeholder="['Start Time', 'End Time']" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD"/></filterComponent>
                    </div>
                </div>
                <div class="list_top_button_content">
                    <a-button class="primary_button btn-margin-r-20" type="primary" size="large" @click="searchList()">Seach</a-button>
                    <a-button class="default_button" size="large" @click="resetList()">Reset</a-button>
                    <a-button class="primary_button btn-margin-t-35" type="primary" size="large" @click="addTask()">+Add Task</a-button>
                </div> -->
            </div>
            <div class="list_table_content">
                <a-table :columns="columns" :data-source="collectionList"  @change="changePage" :loading="tableLoading"
                    :pagination="{
                    showSizeChanger:true,
                    current: currentPage,
                    pageSize:pageSize,
                    total: total,
                    showQuickJumper:true,
                    bordered:false,
                    pageSizeOptions:['10','20','50'],
                }">
                    <template v-slot:bodyCell="{column,record, index}" >
                        <template v-if="column.dataIndex === 'operation'">
                            <div class="operate_list">
                                <div class="operate_item" @click="editTask(record)">Detail</div>
                                <!-- <div class="operate_item" @click="deleteTask(record,index)">Delete</div> -->
                            </div>
                        </template>
                        
                    </template>
                </a-table>
            </div>
        </div>

        <a-modal class="edit_modal_component" 
            :destroyOnClose="true"
            v-model:visible="editTaskModal" 
            :footer="null" 
            :title="editTaskTitle"
            width="560px"
            :maskClosable="false"
            :centered="true"
            @cancel="closeTask"
        >
            <a-form ref="formRef" :model="formState" :rules="rules" :layout="'vertical'" >
				<a-row :gutter="[16,16]">
					<a-col :span="12">
						<a-form-item label="Task Name" name="taskName">
							<a-input v-model:value="formState.taskName" size="large" placeholder="Please input task name" />
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="Target Value" name="targetValue">
							<a-input v-model:value="formState.targetValue" size="large" placeholder="Please enter the number of stars"/>
						</a-form-item>
					</a-col>
				</a-row>
				<a-form-item label="Date" name="Date">
					<a-range-picker v-model:value="formState.time" size="large" style="width: 100%;" :placeholder="['Start Time', 'End Time']" :show-time="{ format: 'HH:mm:ss' }"
							format="YYYY-MM-DD HH:mm:ss"
							valueFormat="YYYY-MM-DD HH:mm:ss"/>
				</a-form-item>
				<a-form-item label="Description" name="description">
					<a-textarea :disabled="true" style="max-height: 200px;" v-model:value="formState.description" />
				</a-form-item>
				<a-form-item label="Task List">
					<div class="taskConditionList" v-for="item,index in formState.taskConditionList">
						<!-- <a-checkbox v-model:checked="item.checked" style="margin-bottom: 20px;">
							{{ item.viewName }}
						</a-checkbox> -->
						<div class="taskConditionList-title">{{ item.viewName }}</div>
						<div class="taskConditionList-item">
							<div class="">Condition Field:</div>
							<!-- <a-input v-model:value="item.conditionValue" size="large" placeholder="Please input conditionValue"/> -->
							<a-input :disabled="true" v-model:value="item.conditionField" size="large" placeholder="Please input condition value"/>
							<!-- <a-select style="flex: 1;" v-model:value="item.conditionField" size="large" :options="taskTypeList" placeholder="Please select Fashion Attributes"></a-select> -->
						</div>
						<div class="taskConditionList-item">
							<div>Condition Operator:</div>
							<a-input :disabled="true" v-model:value="item.conditionOperator" size="large" placeholder="Please input condition operator"/>
						</div>
						<div class="taskConditionList-item">
							<div>Condition Value:</div>
							<a-input :disabled="!(isEdit.indexOf(item.id)>-1)" v-model:value="item.conditionValue" size="large" placeholder="Please input total prices"/>
						</div>


						<!-- <div class="taskConditionList-item">
							<div>TotalPrices:</div>
							<a-input v-model:value="item.conditionValue" size="large" placeholder="Please input total prices"/>
						</div> -->
					</div>
				</a-form-item>
				<!-- <a-form-item label="Task Time" :title="'Mission Time'" name="time">
					<a-range-picker 
						size="large"
						style="width:100%"
						v-model:value="formState.time" 
						:placeholder="['Start Time', 'End Time']"
						format="YYYY-MM-DD" 
						valueFormat="YYYY-MM-DD"
					/>
				</a-form-item> -->
				
				
            </a-form>
            <div class="modal_button_list">
                 <a-button class="default_button btn-margin-r-20" size="large" @click="closeTask">Cancel</a-button>
                 <a-button class="primary_button" type="primary" size="large" @click="confirmSubmit">Submit</a-button>
            </div>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { defineComponent,ref,reactive,toRefs,UnwrapRef,onMounted,createVNode } from "vue";
import filterComponent from '@/component/filterComponent.vue'
import { Moment } from 'moment';
import { message,Modal } from "ant-design-vue";
import { WarningOutlined } from '@ant-design/icons-vue';
import { Https } from "@/tool/https";
import { formatTime, startTime, endTime } from "@/tool/util"
import { Item } from "ant-design-vue/lib/menu";

export default defineComponent({
    name:'taskManage',
    components:{filterComponent},
    setup(){
        let filter:any =  reactive({
            name:'',
			time:'',
            addTime:ref<Moment[]>([])
        })
		let setTime = (startTime:any,endTime:any)=>{
			return endTime
		}
		let isEdit = [3,4,5,7]
        let tableLoading = ref(false)
        let taskTypeList:any = ref([
            { value:'CUSTOM',task:'greater than'},
            { value:'NEW_PRODUCT',task:'less than'},
            { value:'SALE',task:'equal to'},
        ])
        let columns = reactive([
            { title: 'Task Name', align:'center', ellipsis: true,  dataIndex: 'taskName', key: 'taskName' },
            { title: 'Target Value', align:'center', ellipsis: true,  dataIndex: 'targetValue', key: 'targetValue' },
            // { title: 'Task Product Counts', align:'center', ellipsis: true,  dataIndex: 'counts', key: 'counts' },
            { title: 'Add Time', align:'center', ellipsis: true,  dataIndex: 'createTime', key: 'createTime',customRender:(record:any)=>{
                // let time = formatTime(record.text / 1000, 'YYYY-MM-DD hh:mm:ss')
				let time = record.text.split('T')[0]+' '+record.text.split('T')[1]
                return time },
            },
			{ title: 'startTime', align:'center', ellipsis: true,  dataIndex: 'startTime', key: 'startTime',customRender:(record:any)=>{
                // let time = formatTime(record.text / 1000, 'YYYY-MM-DD hh:mm:ss')
				let time = record.text.split('T')[0]+' '+record.text.split('T')[1]
                return time },
            },
			{ title: 'endTime', align:'center', ellipsis: true,  dataIndex: 'endTime', key: 'endTime',customRender:(record:any)=>{
                // let time = formatTime(record.text / 1000, 'YYYY-MM-DD hh:mm:ss')
				let time = record.text.split('T')[0]+' '+record.text.split('T')[1]
                return time },
            },
            {
                title: 'Actions',
                key: 'operation',
                align:'center', 
                fixed: 'right',
                width: 150, 
                dataIndex:'operation',
              
            },
        ])
        let collectionList = ref([])
        let currentPage = ref(1)
        let pageSize = ref(10)
        let total = ref(1)
        let editTaskModal = ref(false)
        let editTaskTitle = ref('Add Task')
        let formRef = ref();
        let formState:any = ref({
            id: '',
            taskName: '',
			description:'',
			taskConditionList:[],
			targetValue:1,
			time:ref([]),
        });
        let rules = reactive({
            taskName: [
                { required: true, message: 'Please input task name', trigger: 'blur' },
            ],
			targetValue: [
                { required: true, message: 'Please enter the number of stars', trigger: 'blur' },
            ],
			time: [
                { required: true, message: 'Please enter the task time', trigger: 'blur' },
            ],
        })
		// let conditionList = ref([
		// 	{ viewName: '数量', conditionOperator: 'type' ,checked:false, conditionValue:'1', conditionField:'greater than'},
		// 	{ viewName: '价格', conditionOperator: 'createUserName' ,checked:false, conditionValue:'1', conditionField:'greater than'},
		// 	{ viewName: '指定衣服', conditionOperator: 'SpecifiedClothing' ,checked:false, conditionValue:'1', conditionField:'greater than'},
		// ])
        let changePage = (e:any) =>{
            currentPage.value = e.current
            pageSize.value = e.pageSize
            getTaskist()
        }

        let closeTask = () =>{
            formState.value = {
				id: '',
				description:'',
				taskName: '',
				taskConditionList:[],
				targetValue:0,
				time:[],
            }
            editTaskModal.value = false
        }

        let addTask = () =>{
            editTaskTitle.value = 'Add Task'
            editTaskModal.value = true
        }

        let editTask = (data:any,) =>{
            editTaskModal.value = true
            editTaskTitle.value = 'Edit Task'
            formState.value = {
                id: data.id,
                taskName: data.taskName,
                description: data.description,
				targetValue:data.targetValue,
				taskConditionList:data.taskConditionList,
				// time:[1726711071,1726721071],
				time:[data.startTime.split('T')[0]+' '+data.startTime.split('T')[1],data.endTime.split('T')[0]+' '+data.endTime.split('T')[1]],
            }
        }

        let getTaskist = () =>{
            let data = {
                page:currentPage.value,
                size:pageSize.value
            }
            tableLoading.value = true
			Https.axiosPost(Https.httpUrls.salesIncentivesQueryPage, data).then(
                (rv: any) => {
                    if (rv) {
                        tableLoading.value = false
                        collectionList.value = rv.content
                        total.value = rv.total
                    }
                }
            );
        }
        let confirmSubmit = () =>{
            let data = {
                ...formState.value,
                timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,
            }
			data.startTime = data.time[0]
			data.endTime = data.time[1]
            formRef.value.validate().then(()=>{
                submit()
            })
            let submit = () => {
                Https.axiosPost(Https.httpUrls.salesIncentivesAddTask, data).then(
                    (rv: any) => {
                        if (rv) {
                            let tip = !formState.value.id ? 'Task added successfully' :'Edit task successfully'
                            message.success(tip)
                            resetList()
                            closeTask()
                        }
                    }
                );
            }
                
        }

        let searchList = () =>{
            currentPage.value = 1
            getTaskist()
        }

        let resetList = () =>{
            currentPage.value = 1
            filter.name = ''
            filter.addTime = ref<Moment[]>([])
            getTaskist()
        }

        let deleteTask = (data:any,index:any) =>{
            let confirmDelete = (data:any,index:any) =>{
                let newData = {
                    id:data.id
                }
                // Https.axiosPost(Https.httpUrls.taskDelete, newData).then(
                //     (rv: any) => {
                //         if (rv) {
                //             message.success('Delete success')
                //             collectionList.value.splice(index,1)
                //         }
                //     }
                // );
            }
            Modal.confirm({
                    title: "Are you sure about the task? The task associated with the product will become invalid after deletion!",
                    icon: createVNode(WarningOutlined),
                    class:'confirm_style',
                    okText: 'Ok',
                    cancelText: 'Cancel',
                    // centered:true,
                    onOk() {
                       confirmDelete(data,index)
                    }
                });
        }
        onMounted(() => {
           getTaskist()
        })
        
  
        return {
            ...toRefs(filter),
			isEdit,
			setTime,
            tableLoading,
            taskTypeList,
            columns,
            collectionList,
            currentPage,
            pageSize,
            total,
            editTaskModal,
            editTaskTitle,
            formRef,
            formState,
            rules,
            changePage,
            closeTask,
            addTask,
            editTask,
            confirmSubmit,
            searchList,
            resetList,
            deleteTask
        }
        
    },
   
});
</script>
<style lang="less" scoped>
.task_manage_page{
    padding-left: 28px;

   .operate_list{
       display: flex;
       justify-content: space-between;
	   justify-content: center;
       .operate_item{
            font-size: 14px;
            font-family: Roboto;
            font-weight: 400;
            color: #343579;
            cursor: pointer;
       }
   }
}
.taskConditionList{
	margin-bottom: 24px;
	background: #f7f8fc;
	border: 1px solid #DFDFDF;
	padding: 20px;
	.taskConditionList-title{
		width: 100%;
		text-align: center;
		margin-bottom: 20px;
	}
	.taskConditionList-item{
		display: flex;
		width: 100%;
		align-items: center;
		margin-bottom: 24px;
		>div{
			width: 140px;
			flex-shrink: 0;
		}
	}
	.taskConditionList-item:last-child{
		margin: 0;
	}
}
</style>