<template>
    <div flex class="content">
        <div class="content-left">
            <div style="">
                <p class="left-title"><span>任务下发</span></p>
                <base-form :formRow="taskFormRow" @elDialogClick="elDialogClick" @onSelect="selectChange" ref="taskForm"
                    :spanWidth="'60px'" :spanNumber="24" :isFunBtn="false" style="padding: 0 20px;">
                </base-form>
            </div>
            <div>
                <p class="left-title"><span>任务内容</span></p>
                <el-input type="textarea" :rows="8" placeholder="请输入内容" v-model="textarea"></el-input>
            </div>
            <div style="position: absolute;right: 10px;bottom: 10px;">
                <el-button type="danger" size="small" @click="del">删除</el-button>
                <el-button type="danger" size="small" @click="clear">清空</el-button>
                <el-button type="primary" size="small" @click="submitForm">提交</el-button>
            </div>
        </div>

        <base-layout :buttonList="buttonList" :isPage="true" @onFuncBtn="onFuncBtn"
            style="flex:1;position: relative;width: 75%;" @onFixedBtn="onFixedBtn" :showTitle="false"
            :fixedButtonList="fixedButtonList" :fixedButton="true" :defaultButtonSwitch="false" ref="layout"
            @pageChange="onPageChange">
            <div slot="main" slot-scope="{ tableHeight }" style="height: 100%;">
                <div class="query">
                    <el-input clearable v-model="input1" placeholder="项目名称模糊查找" @change="GetBillList">
                    </el-input>
                    <el-input style="margin: 0 10px;" clearable v-model="input2" placeholder="人员模糊查找" @change="GetBillList">
                    </el-input>
                    <el-date-picker style="margin-right:10px;" v-model="startDate" align="right" type="date"
                        placeholder="开始日期" value-format="yyyy-MM-dd">
                    </el-date-picker>
                    <el-date-picker v-model="endDate" align="right" type="date" placeholder="结束日期"
                        value-format="yyyy-MM-dd">
                    </el-date-picker>

                </div>
                <base-table :border="true" :showIndex="false" :slotrow="false" style="overflow-x: auto;"
                    :tableHeight="tableHeight" :tabLoading.sync="tabLoading" :tableData="tableData"
                    :tableColumn="tableColumn" ref="tableData" @doubleClick="doubleClick">
                    <template v-slot:overDate="{ row }">
                        <span>{{ row.overDate | getDate }}</span>
                    </template>
                    <template v-slot:backDate="{ row }">
                        <span>{{ row.backDate | getDate }}</span>
                    </template>
                    <template v-slot:createDate="{ row }">
                        <span>{{ row.createDate | getDate }}</span>
                    </template>
                    <template v-slot:isOverName="{ row }">
                        <span
                            :style="{ 'color': row.isOverName == '未完成' || row.isOverName == '未反馈' ? '#ff0001' : '#1a95ff' }">
                            {{ row.isOverName }}</span>
                    </template>
                    <template v-slot:level="{ row }">
                        <div class="color">
                            <div class="level" :class="{
                                'active1': row.level == 1,
                                'active2': row.level == 2,
                                'active3': row.level == 3
                            }">
                                {{ row.level }}
                            </div>
                        </div>
                    </template>
                </base-table>
            </div>
        </base-layout>
        <base-quantity-person ref="baseQuantityPerson" @personConfirmClick="personConfirmClick"></base-quantity-person>
        <base-dynamic-column ref="baseDynamicColumn" :id="167"></base-dynamic-column>
    </div>
</template>

<script>
// 组件
import baseLayout from '@/components/base/baseLayout'
import baseTable from '@/components/base/baseTable'
import baseDialog from '@/components/base/BaseNewDialog'
import baseForm from '@/components/base/baseNewForm'
import baseQuantityPerson from '@/components/base/baseQuantityPerson'
import baseDynamicColumn from '@/components/base/baseDynamicColumn'
import { dataDictionaryGetBillList } from "@/api/apis/dataDictionary";
import { GetBillList, SaveData, DelData, DetialData } from "@/api/apis/myJob";
import { GetDataSourcePerson, } from "@/api/apis/documentManagement";
import configData from './configData';
import { projectList, projectDetail, projectSaveData, projectDelData, projectProMemberDelData, projectProPhaseDelData } from "@/api/apis/projectManagement";
export default {
    components: {
        baseLayout, baseTable, baseDialog, baseForm, baseQuantityPerson, baseDynamicColumn
    },
    data() {
        return {
            //
            buttonList: [
                { menuName: '查询', },
                { menuName: '本周', },
                { menuName: '上周', },
                { menuName: '下周', },
            ],
            fixedButtonList: [
                {
                    icon: 'el-icon-s-operation',
                    title: '筛选'
                }
            ],
            pageModel: {//分页
                limit: 20,
                page: 1
            },
            // tableColumn: configData.tableColumn,//表头
            tableColumn: [],
            tableData: [],//表数据
            tabLoading: false,
            //
            textarea: '',
            taskFormRow: configData.taskFormRow,
            //
            input1: "",
            input2: "",
            startDate: "",
            endDate: '',
            delState: "",//双击状态
            id: '',//双击行数据id
            dropList1: [],//项目下拉
            billid: '',
            createPerson: '',
            loginPerson: JSON.parse(localStorage.getItem("Admin-Info")).personName,
        };
    },
    mounted() {
        this.getDates()
        this.init()
    },
    filters: {
        getDate(value) {
            if (!value) {
                return ''
            }
            return value.split('T')[0]
        },
    },
    methods: {
        // 页面初始化
        init() {
            this.GetBillList();
            this.getProjectList();
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var dates = date.getDate();
            let time = year + "-" + month + "-" + dates;
            this.$refs.taskForm.getField("overDate", time);
            this.$refs.taskForm.getField("level", 3);
        },
        onFuncBtn(btnEven) {
            if (btnEven.menuName == "查询") {
            } else if (btnEven.menuName == "本周") {
                this.getDates()
            } else if (btnEven.menuName == "上周") {
                this.getLastWeek()
            } else if (btnEven.menuName == "下周") {
                this.getNextWeek()
            }
            this.GetBillList()
        },
        onFixedBtn(item) {
            if (item.title == "筛选") {
                this.$refs.baseDynamicColumn.screen = true
                this.$refs.baseDynamicColumn.init()
            }
        },
        elDialogClick(row) {
            this.$refs.baseQuantityPerson.openDialog()
        },
        selectChange($event, index, indexRow, val) {
            // console.log($event, index, indexRow, val);
            this.$refs.taskForm.getField("projectID", val.value)
        },
        //行双击事件
        doubleClick(row) {
            this.delState = true
            this.DetialData(row)
            // console.log(row);
            this.createPerson = row.cPersonName
        },
        //提交
        async submitForm() {
            // console.log(this.billid, "22")
            let data = {
                dataMain: {
                    ...this.$refs.taskForm.ruleForm,
                    billid: this.billid ? this.billid : "00000000-0000-0000-0000-000000000000",
                    content: this.textarea
                }
            }
            let res = await SaveData(data);
            if (res.code == 1) {
                this.$vmNews("保存成功", "success");
                this.GetBillList()
                this.clear()
            }
        },
        async delete() {
            let res = await DelData({ id: this.billid });
            if (res.success == "true") {
                this.$vmNews("删除成功", "success");
                this.GetBillList()
                this.clear()
            }
        },
        //删除
        del() {
            if (this.delState) {
                if (this.createPerson == this.loginPerson) {
                    this.$delConfirm().then(res => {
                        this.delete()
                    })
                } else {
                    this.$vmNews('创建人与登录人不是同一人,不允许删除!', 'warning')
                }

            } else {
                this.$vmNews('请双击选择右侧列表中一条数据!', 'warning')
            }
        },
        async delete() {
            let res = await DelData({ id: this.billid });
            if (res.success == "true") {
                this.$vmNews("删除成功", "success");
                this.GetBillList()
                this.clear()
            }
        },
        async DetialData(row) {
            let res = await DetialData({ id: row.billid, op: "" });
            if (res.code == 1) {
                this.$nextTick(() => {
                    this.textarea = row.content
                    this.$refs.taskForm.choiceAssignment(res.data[0])
                })
                this.billid = res.data[0].billid
            }
        },
        clear() {
            this.$refs.taskForm.resetFields();
            this.textarea = '';
            this.delState = false;

        },
        // tableRowClassName(obj, callback) {
        //     if (obj.row.isOverName == "延期完成" || obj.row.isOverName == "完成" || obj.row.isOverName == "正常完成" || obj.row.isOverName == "提前完成") {
        //         callback('success-row')
        //     } else {
        //         callback('warning-row')
        //     }
        // },
        //任务下发列表
        async GetBillList() {
            this.billid = '';
            this.tabLoading = true;
            let params = {
                ...this.pageModel,
                Sequence: "descending",
                SequenceName: "overDate",
                projectName: this.input1,
                pPersonName: this.input2,
                startDate: this.startDate,
                endDate: this.endDate
            }
            const res = await GetBillList(params);
            if (res.code == 1) {
                this.$refs.layout.setPageTotal(res.data[0]);
                this.tableData = res.data[1];
                this.tabLoading = false;
            }
            const el = await GetDataSourcePerson({ billKindID: '167' })
            if (el.code == 1) {
                this.tableColumn = el.data[1].length == 0 ? el.data[0] : el.data[1]
                this.tableColumn.forEach(el => {
                    el.tooltip = true
                });
            }
        },
        //弹窗批量获取所需人员
        personConfirmClick(arr) {
            let arrListId = [];
            let arrListName = [];
            arr.forEach(el => {
                let arr = {
                    label: el.p_PersonName,
                    value: el.p_PersonID,
                };
                arrListName.push(arr.label);
                arrListId.push(arr.value);

            })
            this.$refs.taskForm.getField("personName", arrListName.join(","))
            this.$refs.taskForm.getField("personID", arrListId.join(","))
        },
        //获取下拉项目名称
        async getProjectList() {
            let params = {
                ...this.pageModel,
                Sequence: "",
                SequenceName: "",
            };
            let res = await projectList(params);
            if (res.code == 1) {
                let arrList = [];
                let projectIdList = []
                if (res.data[0] > 0) {
                    res.data[1].forEach((el) => {
                        let arr = {
                            label: el.projectName,
                            value: el.billid,//
                            // projectID: el.billid,
                        };
                        arrList.push(arr);
                        projectIdList.push(arr.billid)
                    });
                }
                this.dropList1 = arrList;
                this.taskFormRow[0].elCol[0].options = arrList;
            }
        },
        // 分页
        onPageChange(model) {
            this.pageModel.page = model.page;
            this.pageModel.limit = model.limit;
            this.getProjectList()
        },
        getDates() {
            const today = new Date();
            // 获取当前日期的周几（0 表示周日，1 表示周一，以此类推）
            const dayOfWeek = today.getDay();
            // 计算本周的开始日期和结束日期
            const startOfThisWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - dayOfWeek);
            const endOfThisWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() + (6 - dayOfWeek));
            this.startDate = this.formatDate(startOfThisWeek);
            this.endDate = this.formatDate(endOfThisWeek);
        },
        getLastWeek() {
            const inputDate = new Date(this.startDate);
            const previousWeekStart = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate() - 7);
            const previousWeekEnd = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate() - 1);
            this.startDate = this.formatDate(previousWeekStart);
            this.endDate = this.formatDate(previousWeekEnd);
        },
        getNextWeek() {
            // console.log(this.startDate);
            const inputDate = new Date(this.startDate);
            const startOfNextWeek = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate() + 7);
            const endOfNextWeek = new Date(inputDate.getFullYear(), inputDate.getMonth(), inputDate.getDate() + 13);
            this.startDate = this.formatDate(startOfNextWeek);
            this.endDate = this.formatDate(endOfNextWeek);
            // console.log(this.formatDate(startOfNextWeek), this.formatDate(endOfNextWeek));
        },
        formatDate(value, type) {
            // 计算日期相关值
            let time = typeof value == 'number' ? new Date(value) : value;
            let Y = time.getFullYear();
            let M = time.getMonth() + 1;
            let D = time.getDate();
            // 如果传递了type的话
            if (type == undefined) {
                return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D);
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.content {
    height: 100%;
    padding: 0 10px;

    .content-left {
        overflow-y: auto;
        position: relative;
        width: 25%;
        padding: 5px;
        border: 1px solid #d5d7d6;
        border-radius: 10px;
        margin: 0px 10px 10px 0;

    }

    .left-title {
        padding: 20px 10px;
        font-size: 16px;
        font-family: PingFangSC-Semibold, PingFang SC;
        color: #000;

        ::v-deep .el-form-item__label {
            font-size: 16px;
        }

        span {
            padding-left: 8px;
            border-left: 3px solid #2261F6;
        }
    }

    .query {
        display: flex;
        position: absolute;
        top: 10px;

        ::v-deep .el-input__inner {
            width: 150px;
        }
    }

    .color {
        // width: 80px;
        text-align: center;

        .level {
            border-radius: 50%;
            display: inline-block;
            width: 23px;
            height: 23px;
            font-weight: 600;
        }

        .active1 {
            // border: 2px solid #e1433a;
            background: #e1433a;
            color: #fff;
        }

        .active2 {
            // border: 2px solid #FCC102;
            background: #FCC102;
            color: #fff;
        }

        .active3 {
            // border: 2px solid #1a95ff;
            background: #1a95ff;
            color: #fff;
        }
    }

}
</style>