<template>
    <div class="testdiv">
        <div class="divborder newSearchDiv">
            <div class="filter">
                <label>{{$t(100000)}}：</label>
                <Select
                    class="searchSelect"
                    v-model="depart"
                    clearable
                    @on-change="getkpiList1(depart)"
                >
                    <Option
                        v-for="(item,key) in departList"
                        :value="item.id"
                        :key="key"
                    >{{ item.title }}</Option>
                </Select>
            </div>
            <div class="filter">
                <label>{{$t(950384)}}：</label>
                <Select class="searchSelect" v-model="kpiIndex" clearable>
                    <Option
                        v-for="(item,key) in kpiList"
                        :value="item.title"
                        :key="key"
                    >{{ item.title }}</Option>
                </Select>
                <!-- <Input class="divSearch" v-model="kpiIndex" clearable placeholder /> -->
            </div>
            <div class="filter">
                <label>{{$t(900908)}}：</label>
                <DatePicker
                    class="searchInput middleWidth"
                    type="daterange"
                    :value="dateTime"
                    @on-change="selectDate"
                ></DatePicker>
            </div>

            <div class="filter">
                <label>{{$t(950404)}}：</label>
                <Select class="searchSelect" v-model="exception" clearable>
                    <Option
                        v-for="item in exceptionlst"
                        :value="item.id"
                        :key="item.id"
                    >{{ item.title }}</Option>
                </Select>
            </div>
            <div class="searchBtn">
                <Button
                    class="twoWord"
                    type="primary"
                    icon="ios-search"
                    @click="search(page,pagesize)"
                >{{$t('1001')}}</Button>
                <Button type="success" class="twoWord" icon="md-add-circle" @click="add()">{{$t('1002')}}</Button>
                <Button type="warning" class="twoWord intervalRight" icon="ios-create-outline" @click="plan()">{{$t('1003')}}</Button>
                <!-- <Button type="warning" icon="ios-create" @click="record()" v-text="$t(950379)">处理完成</Button> -->
                <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="downexcel()">{{$t('1007')}}</Button>
            </div>
        </div>

        <div class="divborder newTableDiv">
            <Table
                class="tableClass"
                @on-current-change="handleRowChange"
                highlight-row
                :data="tableData"
                :columns="tableColumns"
                ref="currentRowTable"
            ></Table>
            <div class="pageDiv">
                <div class="pageDirection">
                    <Page
                        :total="total"
                        :current="page"
                        @on-change="changePage"
                        show-elevator
                        show-sizer
                        show-total
                        @on-page-size-change="handlePageSize"
                        :page-size-opts="[10,20,30,40,100]"
                    ></Page>
                </div>
            </div>
        </div>

        <!-- 指定行动计划 start-->
        <Modal class="newModalClass"  :title="planTitle"
         v-model="modalPlan"
         :styles="{width:'600px'}"
         @on-visible-change = "listenModal"
         >
            <div class="bodyModal" style="height:380px;">
                <div class="filter">
                    <label><i>*</i>{{$t(950411)}}：</label>
                    <DatePicker
                        class="searchInput"
                        v-model="obj.planTime"
                        type="datetime"
                        @on-change="selectDate1($event)"
                    ></DatePicker>
                </div>
                <div class="filter">
                    <label><i>*</i>{{$t(100000)}}：</label>
                    <Select
                        class="searchSelect"
                        v-model="obj.departid"
                        clearable
                        @on-change="getuserList()"
                    >
                        <Option
                            v-for="(item,key) in departList"
                            :value="item.id"
                            :key="key"
                        >{{ item.title }}</Option>
                    </Select>
                </div>
                <div class="filter">
                    <label><i>*</i>{{$t(950377)}}：</label>
                    <Select class="searchSelect" v-model="obj.responsibleID" clearable>
                        <Option
                            v-for="(item,key) in userList"
                            :value="item.id"
                            :key="key"
                        >{{ item.name }}</Option>
                    </Select>
                </div>

                <div class="filter" style="height:75px">
                    <label><i>*</i>{{$t('5500016')}}：</label>
                    <Input
                        class="searchInput MaxWidth"
                        type="textarea"
                        v-model="obj.desc1"
                        :autosize="{minRows: 2,maxRows: 2}"
                    />
                </div>
                <div class="filter" style="height:75px">
                    <label><i>*</i>{{$t(90000059)}}：</label>
                    <Input
                        class="searchInput MaxWidth"
                        type="textarea"
                        v-model="obj.cause"
                        :autosize="{minRows: 2,maxRows: 2}"
                    />
                </div>
                <div class="filter" style="height:75px;">
                    <label><i>*</i>{{$t(90000060)}}：</label>
                    <Input
                        class="searchInput MaxWidth"
                        type="textarea"
                        v-model="obj.record"
                        :autosize="{minRows: 2,maxRows: 2}"
                    />
                </div>
                <div class="filter">
                    <label>{{$t('99200023')}}：</label>
                    <DatePicker
                        class="searchInput"
                        v-model="obj.excutetime"
                        type="datetime"
                        @on-change="selectDate_exc($event)"
                    ></DatePicker>
                </div>
                <div class="filter">
                    <label>{{$t('99200024')}}：</label>
                    <DatePicker
                        class="searchInput"
                        v-model="obj.checktime"
                        type="datetime"
                        @on-change="selectDate_check($event)"
                    ></DatePicker>
                </div>
                <div class="filter">
                    <label>{{$t('99200025')}}：</label>
                    <DatePicker
                        class="searchInput"
                        v-model="obj.solveTime"
                        type="datetime"
                        @on-change="selectDate_slove($event)"
                    ></DatePicker>
                </div>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="modalPlan = false">{{$t(1033)}}</Button>
                <Button type="primary" size="large" @click="planPost">{{$t(1011)}}</Button>
            </div>
        </Modal>
        <!-- 指定行动计划 end-->

        <!-- 处理过程记录 start-->
        <Modal class="newModalClass" :title="recordTitle" v-model="modalRecord" :styles="{width:'500px'}">
            <div class="bodyModal" style="height:200px;">
                <div class="filter">
                    <label>{{$t(950414)}}:</label>
                    <Checkbox v-model="obj.isSolvenum" style="width:50px;">{{$t(1000020)}}</Checkbox>
                </div>
            </div>
            <div slot="footer">
                <Button type="text" size="large" @click="modalRecord = false">{{$t(1033)}}</Button>
                <Button type="primary" size="large" @click="recordPost">{{$t(1011)}}</Button>
            </div>
        </Modal>
        <!-- 处理过程记录 end-->
    </div>
</template>

<script>
import moment from 'moment';
import axios from '@/libs/api.request';
export default {
    // name: 'tree_select_page',
    components: {},
    data () {
        return {
            headers: {
                // 上传请求头添加
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            morecondition: false,
            dateTime: '', // 日期范围
            starttime: '', // 开始时间
            endtime: '',
            depart: 0, // 部门
            departList: [], // 部门列表
            departLists: [], // 部门列表
            kpiIndex: '', // kpi指标
            status: 0, // 维护状态
            exception: 0, // 处理状态
            addTitle: this.$t(1002),
            editTitle: this.$t(1003),
            planTitle: this.$t(1003),
            recordTitle: this.$t(950410),
            modalAdd: false, // 添加弹窗
            modalEdit: false, // 编辑弹窗
            modalPlan: false, // 指定行动计划弹窗
            modalRecord: false, // 处理过程记录弹窗
            action:
                axios.publicPath +
                'kpi/upload/UploadExcel?templateName=KpiTaskAct',
            addObj: {
                // 添加弹窗
                depart: '',
                kpiIndex: '',
                targetValue: '',
                unit: '',
                judgement: '',
                datetime: '',
                actual: ''
            },
            actionType: 1, // 1添加 2编辑
            kpiIndexList: [], // 指标列表
            userList: [], // 人员列表
            page: 1,
            pagesize: 10,
            total: 0,
            obj: {}, // 选中行
            tableData: [], // 列表数据
            exceptionlst: [],
            tableColumns: [
                {
                    type: 'index2',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    // fixed: 'left',
                    width: 80
                },
                {
                    title: this.$t(100000),
                    key: 'depart',
                    // fixed: 'left',
                    width: 110
                },
                {
                    title: this.$t(90000063),
                    key: 'cycle',
                    // fixed: 'left',
                    width: 110
                },
                {
                    title: this.$t(950384),
                    key: 'kpiValue',
                    // fixed: 'left',
                    width: 110
                },
                {
                    title: this.$t(600532),
                    key: 'datetime',
                    // fixed: 'left',
                    width: 110
                },
                {
                    title: this.$t(950386),
                    key: 'targetValue',
                    // fixed: 'left',
                    width: 110
                },
                {
                    title: this.$t(950408),
                    key: 'actualValue',
                    // fixed: 'left',
                    width: 110
                },
                {
                    title: this.$t(90000073),
                    key: 'judgementLogic',
                    // fixed: 'left',
                    width: 200
                },
                {
                    title: this.$t(200017),
                    key: 'unit',
                    // fixed: 'left',
                    width: 80
                },
                {
                    title: this.$t(1030),
                    key: 'remark',
                    // fixed: 'left',
                    width: 150
                },
                {
                    title: this.$t(5500016),
                    key: 'desc1',
                    width: 300
                },
                {
                    title: this.$t(90000059),
                    key: 'cause',
                    width: 300
                },
                {
                    title: this.$t(90000060),
                    key: 'record',
                    width: 300
                },
                {
                    title: this.$t(950377),
                    key: 'username',
                    width: 120
                },
                {
                    title: this.$t(950411),
                    key: 'planTime',
                    width: 160
                },
                {
                    title: this.$t(5500018),
                    key: 'excutetime',
                    width: 160
                },
                {
                    title: this.$t(5500019),
                    key: 'checktime',
                    width: 160
                },
                {
                    title: this.$t(5500017),
                    key: 'solveTime',
                    width: 150
                },
                {
                    title: this.$t(950404),
                    key: 'doStatus',
                    width: 150,
                    render: (h, params) => {
                        var bgColor = '';
                        if (params.row.exception === 1) {
                            bgColor = '#A30014';
                        } else if (params.row.exception === 2) {
                            bgColor = '#BA781F'; // 红BA781F
                        } else {
                            bgColor = '#4B7902';
                        }
                        return h(
                            'div',
                            {
                                style: {
                                    color: '#fff',
                                    backgroundColor: bgColor
                                }
                            },
                            params.row.doStatus
                        );
                    }
                }
            ],
            defaultDepart: 0,
            kpiList: [],
            act: false,
            check: false,
            deal: false
        };
    },
    created () {
        this.inittime(); // 初始化
        this.getDepartList(); // 获取部门
        // 格式化表格样式
  	this.tableColumns = this.$time.initTableTitle(this.tableColumns)
        axios
            .request({
                url: '/config/ProjectSection/GetCurrentDepart',
                method: 'get'
            })
            .then(res => {
                if (res.data.ret === 1) {
                    this.defaultDepart = res.data.data.id;
                    this.depart = this.defaultDepart;
                    this.search(this.page, this.pagesize);
                    this.getkpiList1(this.depart);
                }
            });
        this.loadException();
    },
    methods: {
        loadException () {
            // if (this.status == 2) {
            this.exceptionlst = [
                { id: 1, title: this.$t(900629) },
                { id: 2, title: this.$t(950378) },
                { id: 3, title: this.$t(950379) }
            ];
        },
        inittime () {
            // 时间赋值
            var date = new Date();
            var start = this.timestampToTime(
                date.getTime() - 3600 * 1000 * 24 * 7
            );
            var end = this.timestampToTime(date.getTime());
            this.dateTime = [start, end];
        },
        selectDate (e) {
            this.dateTime = [e[0], e[1]];
        },
        selectDate1 (e) {
            if (this.modalAdd) {
                this.addObj.datetime = e;
            }
            if (this.modalEdit) {
                this.obj.datetime = e;
            }
            if (this.modalPlan) {
                this.obj.planTime = e;
            }
        },
        selectDate_exc (e) {
            this.obj.excutetime = e;
        },
        selectDate_check (e) {
            this.obj.checktime = e;
        },
        selectDate_slove (e) {
            this.obj.solveTime = e;
        },
        getkpiList1 (section) {
            axios
                .request({
                    url: '/kpi/ItemDisplay/GetItem?section=' + section,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.kpiList = res.data.data;
                    }
                });
        },
        // 获取部门
        getDepartList () {
            axios
                .request({
                    url: '/config/ProjectUser/getUserDepartment',
                    method: 'get'
                })
                .then(res => {
                    this.departList = [];
                    if (res.data.ret === 1) {
                        if (res.data.data.length !== 0) {
                            this.departList = res.data.data;
                            this.departLists = res.data.data;
                        }
                    }
                });
        },
        // 获取人员列表
        getuserList () {
            axios
                .request({
                    url:
            '/config/user/GetUsers?page=1&pagesize=1000000&sectionid=' +
            this.obj.departid,
                    method: 'get'
                })
                .then(res => {
                    this.userList = [];
                    if (res.data.ret === 1) {
                        if (res.data.data.length !== 0) {
                            this.userList = res.data.data;
                            this.obj.responsibleID = this.obj.responsibleID;
                        }
                    }
                });
        },
        search (page, pagesize) {
            if (this.dateTime !== '') {
                this.starttime = this.dateTime[0];
                this.endtime = this.dateTime[1];
            }
            // if (this.status != 2) {
            //   // 只有异常才有异常进度
            //   this.exception = 0;
            // }
            var params = {
                section: this.depart,
                item: this.kpiIndex,
                taskResult: this.status,
                exception: this.exception,
                begin: this.starttime,
                end: this.endtime,
                pagesize: this.pagesize,
                page: this.page
            };
            axios
                .request({
                    url: '/kpi/Tasklist/GetList',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.total = res.data.total;
                        this.page = res.data.page;
                        this.mockTableData(res.data.data);
                    }
                });
        },
        mockTableData (tablelist) {
            let data = [];
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        depart: item.sectionDesc, // 部门
                        kpiValue: item.item, // kpi指标
                        cycle: item.cycle,
                        datetime: item.busidate, // 日期
                        targetValue: item.target, // 目标值
                        unit: item.unit, // 单位
                        actualValue: item.val, // 实际值
                        judgementLogic: item.condition, // 判断逻辑
                        status: item.taskResultDesc, // 维护状态
                        doStatus: item.exceptionStatus, // 处理状态
                        username: item.responsiblePersion, // 责任人
                        responsibleID: item.responsibleID,
                        planTime: item.plantime != null ? item.plantime : '', // 计划时间
                        cause: item.cause, // 根本原因
                        record: item.solution, // 过程记录
                        isSolve: item.resultDesc, // 是否解决
                        isSolvenum: item.result !== 0, // 是否解决
                        solveTime: item.operatetime, // 解决时间
                        id: item.id,
                        actionId: item.actionId, // 行动计划ID
                        taskResult: item.taskResult, // 维护状态
                        exception: item.exception, // 处理状态
                        operaterID: item.operater,
                        section: item.section,
                        responsibleDepart: item.responsibleDepart, // 部门
                        remark: item.remark,
                        desc1: item.desc1,
                        checktime: item.checktime,
                        excutetime: item.excutetime,
                        reposible_sectionId: item.reposible_sectionId
                    });
                }
            });
            this.tableData = data;
        },
        // 根据部门-项目指标
        getKpiList () {
            this.kpiIndexList = [];
            this.addObj.targetValue = '';
            this.addObj.unit = '';
            this.addObj.judgement = '';
            var params = {
                section: this.addObj.depart
            };
            axios
                .request({
                    url: '/kpi/Item/GetItemBySection',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1 && res.data.data.length !== 0) {
                        this.kpiIndexList = res.data.data;
                    }
                });
        },
        // 获取kpi信息
        getKpiInfo (e) {
            if (this.kpiIndexList.length > 0) {
                this.kpiIndexList.forEach(item => {
                    if (item.item === e) {
                        this.addObj.targetValue = item.targetVal;
                        this.addObj.unit = item.unit;
                        this.addObj.judgement =
                            item.condition === 0
                                ? this.$t(950388)
                                : this.$t(950389);
                    }
                });
            }
        },
        // 添加
        add () {
            if (this.obj.id === '' || this.obj.id === undefined) {
                this.$Message.error(this.$t('1017'));
                return false;
            } else {
                this.getuserList()
                this.modalPlan = true
                this.actionType = 1 // 添加
                this.planTitle = this.$t('1002')

                this.obj.departid = this.defaultDepart
                this.obj.planTime = ''
                this.obj.responsibleID = 0
                this.obj.actionId = 0
                this.obj.desc1 = ''
                this.obj.cause = ''
                this.obj.record = ''
                this.obj.excutetime = ''
                this.obj.checktime = ''
                this.obj.solveTime = ''
            }
        },
        listenModal (event) {
            if (this.actionType === 1) {
                if (!event) {
                    // this.$refs.currentRowTable.clearCurrentRow()
                    this.page = 1
                    this.pagesize = 10
                    this.obj.id = ''
                    this.search()
                    return false
                }
            }
        },
        // 指定行动计划
        plan () {
            if (this.obj.id === '' || this.obj.id === undefined) {
                this.$Message.error(this.$t('1017'));
                return false;
            } else {
                if (this.obj.actionId !== 0 && this.obj.exception !== 3) {
                    this.planTitle = this.$t('1003')
                    if (this.obj.reposible_sectionId !== 0) {
                        this.obj.departid = this.obj.reposible_sectionId
                    } else {
                        this.obj.departid = this.obj.responsibleDepart
                            ? this.obj.responsibleDepart
                            : this.defaultDepart;
                    }

                    this.getuserList();
                    this.modalPlan = true;
                    this.actionType = 2 // 编辑
                } else {
                    this.$Message.error(this.$t(5500087));
                    return false;
                }
            }
        },
        planPost () {
            if (
                this.obj.id === 0 ||
                this.obj.responsibleID == 0 ||
                this.obj.responsibleID === undefined ||
                this.obj.planTime === null
            ) {
                this.$Message.error(this.$t('600652'));
                return false;
            }

            var data = {
                TaskId: this.obj.id,
                ActionId: this.obj.actionId,
                Reposible: this.obj.responsibleID,
                Plantime: this.obj.planTime,
                Solution: this.obj.record === null ? '' : this.obj.record,
                Cause: this.obj.cause === null ? '' : this.obj.cause,
                Desc: this.obj.desc1 === null ? '' : this.obj.desc1,
                CheckTime: this.obj.checktime === null ? '' : this.obj.checktime,
                ExcuteTime: this.obj.excutetime === null ? '' : this.obj.excutetime,
                SloveTime: this.obj.solveTime === null ? '' : this.obj.solveTime
            };
            // debugger;
            // 添加
            if (this.actionType === 1) {
                var url = '/kpi/Action/Add'
            } else {
                var url = '/kpi/Action/Modify'
            }

            axios
                .request({
                    url: url,
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.obj = {};
                        this.$Message.success(this.$t('1064'));
                        this.search(this.page, this.pagesize);
                        this.modalPlan = false;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        // 处理过程记录
        record () {
            if (this.obj.taskResult === 2 && this.obj.exception == 2) {
                // this.getuserList();
                this.modalRecord = true;
                this.obj.operaterID = 0;
                this.obj.record = '';
                this.obj.isSolvenum = false;
            } else {
                this.$Message.error(this.$t(950419));
                return false;
            }
            // }
        },
        recordPost () {
            if (
                this.obj.operaterID === '' ||
                this.obj.operaterID === undefined
                // this.obj.record === ""
            ) {
                this.$Message.error(this.$t('600652'));
                return false;
            }

            var data = {
                TaskId: this.obj.id,
                Operater: this.obj.operaterID,
                // Solution: this.obj.record,
                Fxied: this.obj.isSolvenum ? 1 : 0
            };
            axios
                .request({
                    url: '/kpi/ActionResult/Add',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.obj = {};
                        this.$Message.success(this.$t('1064'));
                        this.search(this.page, this.pagesize);
                        this.modalRecord = false;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        // 下载模板
        loadexcel () {
            axios
                .request({
                    url: '/config/download/GetTemplate?name=KpiTaskAct',
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        window.location.href =
                            axios.publicPath + '' + res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        // 导出
        downexcel () {
            if (this.dateTime !== '') {
                this.starttime = this.dateTime[0];
                this.endtime = this.dateTime[1];
            }
            var params = {
                section: this.depart,
                item: this.kpiIndex,
                status: this.status,
                exception: this.exception,
                begin: this.starttime,
                end: this.endtime,
                pagesize: this.pagesize,
                page: this.page
            };
            axios
                .request({
                    url: '/kpi/Tasklist/ExportAll',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        window.location.href =
                            axios.publicPath + '' + res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        handleFormatError (file) {
            // 导入文件类型检查
            this.$Message.error(this.$t(950396) + file.name + this.$t(950397))
        },
        handleSuccess (res, file) {
            // 导入成功函数
            if (res.ret === 1) {
                this.$Message.success(this.$t(950398));
            } else {
                this.$Message.error(this.$t(res.msg));
            }
        },
        handleError () {
            // 导入失败函数
            this.$Message.error(this.$t(950398));
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.obj = currentRow; // 选中行
        },
        handlePageSize (value) {
            this.pagesize = value;
            this.tableData1 = this.search(this.page, this.pagesize);
        },
        changePage (value) {
            this.page = value;
            this.tableData1 = this.search(this.page, this.pagesize);
        },

        // 时间戳转换成时间
        timestampToTime (timeStampe) {
            var date = new Date(timeStampe); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M =
                (date.getMonth() + 1 < 10
                    ? '0' + (date.getMonth() + 1)
                    : date.getMonth() + 1) + '-';
            var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
            // var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getDate()) + ':'
            // var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':'
            // var s = (date.getSeconds() < 10 ? '0' + (date.getMinutes()) : date.getMinutes())
            return Y + M + D;
        }
    }
};
</script>
<style lang="less">
.filter {
    height: 40px;
    label {
        display: inline-block;
        width: 100px;
    }
}
.testdiv {
    width: 100%;
    height: 100%;
}

.filter .divSearch {
    width: 160px;
}
.bodyModal {
    height: 350px;
}
.bodyModal .filter {
    label {
        display: inline-block;
        width: 120px;
    }
}
.bodyModal .modal-input-select {
    width: 200px;
}

.bodyModal .filter .iClass {
    color: red;
    display: inline-block;
    width: 8px;
}
</style>
