<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv">
      <div class="filter">
        <label>{{$t('100000')}}：</label>
        <Select v-model="depart" @on-change="refresh()" clearable class="searchSelect">
          <Option v-for="(item,key) in departList" :value="item.id" :key="key">{{ item.title }}</Option>
        </Select>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="getDiv()">{{$t('1001')}}</Button>
        <Button type="primary" class="twoWord" icon="ios-redo-outline" @click="preLook()">{{$t('90000066')}}</Button>
      </div>
    </div>
    <div class="divborder">
      <div class="screen">
        <div class="screenfactor">
          <div class="buttonall">
            <Button
              type="primary"
              @click="addRow"
              :disabled="rowdisabled1"
              v-text="$t(90000067)"
            >加一行</Button>
            <Button
              type="primary"
              @click="delRow"
              :disabled="rowdisabled2"
              v-text="$t(90000068)"
            >减一行</Button>
            <Button type="success" icon="md-add-circle" @click="add()" v-text="$t(1002)">添加</Button>
            <Button type="warning" icon="md-add-circle" @click="edit()" v-text="$t(1003)">修改</Button>
            <Button type="error" icon="ios-create-outline" @click="del()" v-text="$t(1004)">删除</Button>
            <!-- <Button type="primary" icon="ios-create-outline" @click="save()">保存</Button> -->
          </div>
        </div>
        <div class="rightTop" :style="'width:' + column * 150 + 'px'">
          <div
            v-for="(item,i) in divList"
            class="divScreen"
            :key="i"
            v-on:click="addClass(i+1)"
            v-bind:class="{'isActive':i==current-1}"
            :style="{ background: item.color}"
          >
            <p>{{$t(100000)}}：{{item.sectionDesc}}</p>
            <p>{{$t(950384)}}:{{item.itemDesc}}</p>
            <p>{{$t(90000063)}}：{{item.kpiCycleDesc}}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加 start-->
    <Modal class="newModalClass" :title="addTitle" v-model="modalAdd" :styles="{width:'500px'}">
      <div class="bodyModel">
        <!-- 部门 -->
        <div class="filter">
          <label>{{$t('100000')}}：</label>
          <Select v-model="depart1" clearable class="searchSelect" @on-change="getkpiList(depart1)">
            <Option v-for="(item,key) in departList" :value="item.id" :key="key">{{ item.title }}</Option>
          </Select>
        </div>
        <!-- 指标 -->
        <div class="filter">
          <label><i>*</i>{{$t(950433)}}：</label>
          <Select v-model="kpiIndex1" clearable class="searchSelect">
            <Option v-for="(item,key) in kpiList" :value="item.id" :key="key">{{ item.title }}</Option>
          </Select>
        </div>
        <!-- 选择背景颜色-->
        <div class="filter">
          <label><i>*</i>{{$t('950390')}}：</label>
          <ColorPicker class="searchInput MaxWidth" v-model="color1" recommend />
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="hide()">{{$t('1033')}}</Button>
        <Button type="primary" size="large" @click="addPost">{{$t('1011')}}</Button>
      </div>
    </Modal>
    <!-- 添加 end-->

    <!-- 编辑 start-->
    <Modal class="newModalClass" :title="editTitle" v-model="modalEdit" :styles="{width:'500px'}">
      <div class="bodyModel">
        <div class="filter">
          <label>{{$t('100000')}}：</label>
          <Select v-model="depart1" clearable class="searchSelect" @on-change="getkpiList(depart1)">
            <Option v-for="(item,key) in departList" :value="item.id" :key="key">{{ item.title }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label><i>*</i>{{$t(950433)}}：</label>
          <Select v-model="kpiIndex2" class="searchSelect">
            <Option v-for="(item,key) in kpiList" :value="item.id" :key="key">{{ item.title }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label><i>*</i>{{$t('950390')}}：</label>
          <ColorPicker class="searchInput MaxWidth" v-model="color2" recommend />
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="hide()">{{$t('1033')}}</Button>
        <Button type="primary" size="large" @click="editPost()">{{$t('1011')}}</Button>
      </div>
    </Modal>
    <!-- 编辑 end-->
  </div>
</template>

<script>
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')
            },
            addTitle: this.$t(1002),
            editTitle: this.$t(1003),
            action:
        axios.publicPath + 'kpi/upload/UploadExcel?templateName=KpiTaskAct',
            tableData1: [], // 列表数据
            defaultDepart: 0, // 根据登录人的默认部门,举例是生产部门
            depart: 0,
            departList: [], // 部门列表
            kpiIndex: '', // kpi指标
            modalAdd: false, // 添加弹窗
            modalEdit: false, // 编辑弹窗
            depart1: '', // 添加-部门
            kpiIndex1: '', // 添加-kpi指标
            targetValue1: '', // 添加-目标值
            unit1: '', // 添加-单位
            judgementLogic1: 0, // 添加-判断逻辑
            kpiCycle: [],
            color1: '#F9C279', // 添加-颜色
            isUse1: false, // 添加-是否启用
            color2: '#F9C279', // 编辑-颜色
            divList: [], // 大屏位置
            current: 0, // 选中位置
            page: 1,
            pagesize: 10,
            total: 0,
            obj: {}, // 选中行
            row: 3, // 默认3行
            column: 4, // 默认4列
            rowdisabled1: false,
            rowdisabled2: false,
            kpiList: [], // kpi列表
            screenList: [], // 屏幕已有kpi指标
            kpiIndex2: '122',
            layoutId: 0
        };
    },
    created () {
        this.getDepartList(); // 获取部门
        // this.search(this.page, this.pagesize);
        // 获取登录人部门
        axios
            .request({
                url: '/config/ProjectSection/GetCurrentDepart',
                method: 'get'
            })
            .then(res => {
                if (res.data.ret === 1) {
                    // console.log(res.data);
                    this.defaultDepart = res.data.data.id;
                    this.depart = this.defaultDepart;
                    this.getDiv();
                    this.depart1 = this.defaultDepart;
                    this.getkpiList(this.depart);
                }
            });
    // this.getDivList();
    },
    methods: {
    // 获取部门
        getDepartList () {
            axios
                .request({
                    url: '/config/ProjectUser/getUserDepartment',
                    method: 'get'
                })
                .then(res => {
                    this.departList = [];
                    if (res.data.ret === 1) {
                        if (res.data.data) {
                            if (res.data.data.length !== 0) {
                                this.departList = res.data.data;
                            }
                        }
                    }
                });
        },
        // 获取指标列表
        getkpiList (section) {
            this.kpiList = [];
            axios
                .request({
                    url: '/kpi/ItemDisplay/GetItemList?section=' + section,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        // console.log(res.data.data);
                        this.kpiList = res.data.data;
                        if (this.kpiList.length > 0) {
                            // this.kpiIndex1 = this.kpiList[0].id
                            // this.kpiIndex2 = this.kpiList[0].id
                            //  console.log( " kpindex "+this.kpiIndex1 );
                        }
                    }
                });
        },
        refresh () {
            this.getDiv();
            this.getDivList();
        },

        // 获取布局
        getDiv () {
            if (this.depart == undefined || this.depart == 0) {
                this.$Message.error(this.$t(100239));
                return false;
            }
            axios
                .request({
                    url: '/kpi/ItemLayout/GetSetting?section=' + this.depart,
                    method: 'get'
                })
                .then(res => {
                    // console.log(res.data);

                    if (res.data.ret === 1) {
                        // this.kpiList = res.data.data;
                        this.row = res.data.data.row;
                        this.column = res.data.data.col;
                        this.layoutId = res.data.data.id;
                        this.divList = [];
                        this.getDivList();
                    } else {
                        this.getDivList();
                        let data = {
                            section: this.depart,
                            row: this.row,
                            col: this.column
                        };
                        axios
                            .request({
                                url: '/kpi/ItemLayout/Modify',
                                data,
                                method: 'post'
                            })
                            .then(res => {
                                if (res.data.ret == 1) {
                                    // console.log(res.data.data);
                                    this.$router.go(0);
                                }
                            });
                    }
                });
        },
        // 根据部门获取大屏位置
        getDivList () {
            this.divList = [];
            let total = this.row * 4;
            // console.log(total);
            for (var i = 0; i < total; i++) {
                var arr = {
                    section: '',
                    item: '',
                    position: i + 1,
                    color: '',
                    itemDesc: ''
                };
                this.divList.push(arr);
            }
            var params = {
                section: this.depart
            };
            axios
                .request({
                    url: '/kpi/ItemDisplay/GetPosition',
                    params,
                    method: 'get'
                })
                .then(res => {
                    if (res.data.ret == 1) {
                        if (res.data.data.length !== 0) {
                            // console.log(res.data.data, this.divList);

                            this.screenList = res.data.data;
                            this.divList.forEach(ele => {
                                res.data.data.forEach(v => {
                                    if (ele.position === v.position) {
                                        ele.id = v.id;
                                        ele.item = v.itemId;
                                        ele.section = v.section;
                                        ele.item = v.itemId;
                                        ele.itemSection = v.itemSection;
                                        ele.position = v.position;
                                        ele.color = v.color;
                                        ele.itemDesc = v.itemDesc;
                                        ele.sectionDesc = v.itemSectionDesc;
                                        ele.kpiCycleDesc = v.kpiCycleDesc;
                                    }
                                });
                            });
                        }
                    }

                    // console.log(this.divList);
                });
        },
        // 修改大屏数量
        addRow () {
            this.row++;
            this.rowdisabled2 = false;
            let data = {
                Id: this.layoutId,
                section: this.depart,
                row: this.row,
                col: this.column
            };
            axios
                .request({
                    url: '/kpi/ItemLayout/Modify',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret == 1) {
                        this.getDiv();
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        delRow () {
            if (this.row > 3) {
                let num = (this.row - 1) * 4;
                let arr = this.screenList.every(ele => {
                    return ele.position <= num;
                });
                if (arr == true) {
                    this.row--;
                } else {
                    this.$Message.error(this.$t(90000070));
                    return false;
                }
            } else {
                this.rowdisabled2 = true;
            }

            this.rowdisabled1 = false;

            let data = {
                Id: this.layoutId,
                section: this.depart,
                row: this.row,
                col: this.column
            };
            axios
                .request({
                    url: '/kpi/ItemLayout/Modify',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret == 1) {
                        this.getDiv();
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
            // this.getDivList();
        },
        // 弹窗
        add () {
            if (this.current == 0) {
                this.$Message.error(this.$t(8000008));
                return false;
            }
            if (this.obj.section != '') {
                this.modalAdd = false;
            }
            // 清除数据
            this.depart1 = '';
            this.kpiIndex1 = '';
            this.color1 = '#F9C279';
            this.modalAdd = true;
            this.getkpiList(this.depart);
        },
        addClass: function (index) {
            this.current = index;
            this.obj = this.divList[index - 1];
            // this.getkpiList(this.obj.itemSection);
        },
        // 添加-提交
        addPost () {
            if (this.kpiIndex1 == 0) {
                this.$Message.error(this.$t(90000071));
                return false;
            }
            // console.log('layout:' + this.depart);
            // console.log('default:' + this.defaultDepart);
            var data = {
                ItemId: this.kpiIndex1,
                // Section: this.defaultDepart,
                Section: this.depart,
                BackColor: this.color1,
                Position: this.current,
                Layout: this.layoutId
            };
            // console.log(data);
            axios
                .request({
                    url: 'kpi/ItemDisplay/Add',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('1055'));
                        this.modalAdd = false;
                        this.current = 0;
                        this.getDivList();
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        // 编辑
        edit () {
            // console.log(this.obj);
            // if (this.depart !=this.defaultDepart)
            // {
            //    this.$Message.error(this.$t("1000041"));
            //   return false;
            // }
            if (this.obj.id == '' || this.obj.id == undefined) {
                this.$Message.error(this.$t(90000072));
                return false;
            }
            // else {
            this.depart1 = this.obj.itemSection;
            // this.getkpiList(this.depart1);
            this.current = this.obj.position;
            this.color2 = this.obj.color;
            this.kpiIndex2 = this.obj.item;
            // this.getDivList();
            this.modalEdit = true;
            // }
            // console.log(this.current);
        },
        // 取消编辑
        hide () {
            this.modalAdd = false;
            this.modalEdit = false;
            this.depart1 = '';
            this.current = '';
            this.color2 = '';
            this.kpiIndex2 = '';
            this.obj = {};
        },
        // 编辑提交
        editPost () {
            var data = {
                Id: this.obj.id,
                ItemId: this.kpiIndex2,
                // Section: this.defaultDepart,
                Section: this.depart,
                BackColor: this.color2,
                Position: this.current,
                Layout: this.layoutId
            };
            axios
                .request({
                    url: '/kpi/ItemDisplay/ModifyPosition',
                    data,
                    method: 'post'
                })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.obj = {};
                        this.$Message.success(this.$t('1060'));
                        // this.search(this.page, this.pagesize);
                        this.getDivList();
                        this.modalEdit = false;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        // 删除
        del () {
            // if (this.depart !=this.defaultDepart)
            // {
            //    this.$Message.error(this.$t("1000041"));
            //   return false;
            // }
            let id = this.divList[this.current - 1].id;
            // console.log(id);
            if (this.obj.id == '' || this.obj.id == undefined) {
                this.$Message.error(this.$t('1017'));
                return false;
            }
            axios
                .request({
                    url:
            '/kpi/ItemDisplay/Del?id=' +
            id +
            '&section=' +
            this.depart +
            '&layout=' +
            this.layoutId,
                    method: 'get'
                })
                .then(res => {
                    // console.log(res.data);
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('1058'));
                        this.getDiv();
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
            //   }
            // }
        },
        // 预览
        preLook () {
            this.$router.push({
                path: '/kpis/visualizing',
                query: {
                    id: this.depart
                }
            });
        },

        // 时间戳转换成时间
        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.getHours()) + ':';
            var m =
        (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
        ':';
            var s =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            return Y + M + D + h + m + s;
        }
    }
};
</script>
<style lang="less" scoped>
.testdiv {
  width: 100%;
  height: 100%;
}
.buttonall{
  button{
    margin-right: 15px;
  }
}
.rightTop {
  margin-top: 20px;
  // width: 600px;
  // height: 300px;
  // border: 1px solid #333;
}

.divScreen {
  width: 150px;
  height: 150px;
  border: 1px solid #ddd;
  float: left;
  cursor: pointer;
  color: #fff;
  text-align: center;
  line-height: 114px;
}
.divScreen p {
  height: 30px;
}
.isActive {
  border: 3px solid #2d8cf0;
}

.bodyModel {
  height: 150px;
}
.bodyModel .divLeft {
  border: 1px solid #ddd;
  width: 300px;
  float: left;
}
.bodyModel .divTop {
  border-bottom: 1px solid #ddd;
  height: 50px;
  color: #2d8cf0;
  line-height: 50px;
  padding: 0px 10px;
}
.bodyModel .leftMiddle {
  border-bottom: 1px solid #ddd;
  height: 100px;
  padding: 10px;
}
.bodyModel .leftButtom {
  height: 245px;
  padding: 10px;
}
.bodyModel .divRight {
  border: 1px solid #ddd;
  width: 465px;
  float: left;
  padding: 0;
}
.bodyModel .rightTop {
  padding: 3px;
}
.bodyModel .filter {
  label {
    display: inline-block;
    width: 85px;
  }
}
.bodyModel .filter .iClass {
  color: red;
  display: inline-block;
  width: 8px;
}
.bodyModel .filter .ivu-input-small {
  width: 135px;
}
//  .divScreen {
//   width: 114px;
//   height: 114px;
//   border: 1px solid #ddd;
//   float: left;
//   cursor: pointer;
//   color: #fff;
//   text-align: center;
//   line-height: 114px;
// }
.bodyModel .divRight .isActive {
  border: 3px solid #2d8cf0;
}
.partone,
.partwo {
  display: flex;
}
.partone {
  height: 70px;
  align-items: center;
}
.kpidetail {
  display: flex;
  flex-direction: column;
}

.screen {
  height: 1000px;
  // width: ;
}
</style>
