<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div class="filter">
        <label>{{$t('1025')}}：</label>
        <Cascader
          :data="datalevel"
          :value="leveldata"
          trigger="click"
          change-on-select
          class="searchSelect"
          @on-change="handlelevelchange"
        ></Cascader>
      </div>
      <div class="filter">
        <label>{{$t('960432')}}：</label>
        <Cascader
          :data="datamachine"
          :value="machinedata"
          trigger="click"
          change-on-select
          class="searchSelect"
          @on-change="handlemachinechange"
        ></Cascader>
      </div>
      <div class="filter">
        <label>{{$t('900908')}}：</label>
        <DatePicker
          type="datetimerange"
          format="yyyy-MM-dd HH:mm:ss"
          v-model="index_time"
          class="searchInput MaxWidth"
        ></DatePicker>
      </div>
      <div class="searchBtn">
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search"
          @click="search(1,10)"
        >{{$t('1001')}}</Button>
        <Button type="success" class="twoWord" icon="md-add-circle" @click="add()">{{$t('1002')}}</Button>
        <Button
          type="warning"
          class="twoWord"
          icon="ios-create-outline"
          @click="edit()"
        >{{$t('1003')}}</Button>
        <Button
          type="error"
          class="twoWord intervalRight"
          icon="md-close-circle"
          @click="del()"
        >{{$t('1004')}}</Button>
        <Button
          class="fourWord"
          icon="md-cloud-download"
          @click="loadpdf()"
          type="primary"
        >{{$t('900741')}}</Button>
      </div>
    </div>

    <div class="divborder newTableDiv" id="demo">
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        :columns="tableColumns1"
      ></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>

    <Modal class="newModalClass" :title="$t('960440')" v-model="addmodal" :styles="{width:'400px'}">
      <div class="modal_body">
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('960436')}}：
          </label>
          <Select v-model="addobj.node_name" clearable filterable class="searchSelect">
            <!-- <Option value="1">入固</Option>
            <Option value="2">维修</Option>
            <Option value="3">维护</Option>
            <Option value="4">移动</Option>-->
            <Option value="5">{{$t(100399)}}</Option>
            <Option value="6">{{$t(400016)}}</Option>
            <Option value="7">{{$t(600233)}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('960437')}}：
          </label>
          <Input class="searchInput" type="text" v-model="addobj.node_info" />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('960439')}}：
          </label>
          <Input
            class="searchInput"
            type="number"
            min="0"
            v-model="addobj.node_cost"
            onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
          />
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="addmodelcancel" v-text="$t('1033')">取消</Button>
        <Button type="primary" size="large" @click="adddata" v-text="$t('1011')">确定</Button>
      </div>
    </Modal>

    <Modal class="newModalClass" :title="$t('1044')" v-model="editmodal" :styles="{width:'400px'}">
      <div class="modal_body">
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('960436')}}：
          </label>
          <Select
            v-model="obj.node_name"
            clearable
            filterable
            class="searchSelect"
            :disabled="true"
          >
            <Option :value="1">{{$t(100396)}}</Option>
            <Option :value="2">{{$t(8000047)}}</Option>
            <Option :value="3">{{$t(100397)}}</Option>
            <Option :value="4">{{$t(100398)}}</Option>
            <Option :value="5">{{$t(100399)}}</Option>
            <Option :value="6">{{$t(400016)}}</Option>
            <Option :value="7">{{$t(600233)}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('960437')}}：
          </label>
          <Input
            class="searchInput"
            type="text"
            v-model="obj.node_info"
            style="width:380px"
            :disabled="this.obj.node_name < 5"
          />
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t('960439')}}：
          </label>
          <Input
            class="searchInput"
            type="number"
            v-model="obj.node_cost"
            onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
          />
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="editmodelcancel" v-text="$t('1033')">取消</Button>
        <Button type="primary" size="large" @click="editdata" v-text="$t('1011')">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import axios from '@/libs/api.request';
import moment from 'moment';
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';

export default {
    data () {
        return {
            index_time: [
                moment(new Date().getTime() - 3600 * 1000 * 24 * 1).format(
                    'YYYY-MM-DD '
                ) + '00:00:00',
                moment(new Date().getTime()).format('YYYY-MM-DD ') + '23:59:59'
            ],
            datalevel: [], // 产线层级数据
            leveldata: [], // 产线层级value
            machinedata: [], // 设备层级
            datamachine: [], // 设备层级value
            total: 0, // 初始化数据总数
            page: 1, // 初始页码
            pagesize: 10, // 初始页码条数
            tableData1: [], // 表格数据
            addmodal: false, // 控制添加模态框出现与消失
            addobj: {},
            editmodal: false,
            obj: {},
            editobj: {}, // 深拷贝
            machine: 0, // 当前设备
            tableColumns1: [
                // 表头
                {
                    type: 'index2',
                    title: this.$t('1008'), // 序号
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: 80,
                    align: 'center'
                },
                {
                    title: this.$t('960432'), // 设备
                    key: 'machine_name',
                    align: 'center'
                },
                {
                    title: this.$t('960436'), // 节点名称
                    key: 'nodename',
                    align: 'center'
                },
                {
                    title: this.$t('960437'), // 节点信息
                    key: 'node_info',
                    align: 'center'
                },
                {
                    title: this.$t('960438'), // 节点时间
                    key: 'node_time',
                    align: 'center'
                },
                {
                    title: this.$t('960439'), // 节点成本
                    key: 'node_cost',
                    align: 'center'
                },
                {
                    title: this.$t('900993'), // 操作人
                    key: 'node_operator_name',
                    align: 'center'
                }
            ]
        };
    },
    created () {
        this.initlevel();
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
    },
    methods: {
    // 初始化产线层级
        initlevel () {
            axios
                .request({
                    url: 'config/ProjectLevelSection/GetSectionTree',
                    method: 'get'
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        const arr = [];
                        this.datalevel = res.data.data;
                        arr.push(res.data.data[0].value);
                        this.leveldata = arr;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        initmachine () {
            var params = { section: this.leveldata[this.leveldata.length - 1] };
            axios
                .request({
                    url: '/config/MachineAttribution/GetAttributionDataBySection',
                    params,
                    method: 'get'
                })
                .then((ret) => {
                    if (ret.data.ret === 1) {
                        const arr = [];
                        this.datamachine = ret.data.data;
                        if (ret.data.data.length > 0) {
                            arr.push(ret.data.data[0].machine);
                            this.machinedata = arr;
                        }
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        handlelevelchange (value, selectedData) {
            this.leveldata = value;
            this.machinedata = [];
            this.datamachine = [];
            this.tableData1 = [];
            this.initmachine();
        },
        handlemachinechange (value, selectedData) {
            this.tableData1 = [];
            this.machinedata = value;
            this.machine = value[value.length - 1];
        },
        search (page, pagesize) {
            var machine = this.machine;
            if (machine === 0 || machine === undefined) {
                this.$Message.error(this.$t('9000416'));
                return;
            }
            var start = moment(this.index_time[0]).valueOf() / 1000;
            var end = moment(this.index_time[1]).valueOf() / 1000;
            var data = {
                starttime: start,
                endtime: end,
                machine: machine,
                page: page,
                pagesize: pagesize
            };
            axios
                .request({
                    url: '/config/machinenode/GetNodeData',
                    data,
                    method: 'post'
                })
                .then((ret) => {
                    if (ret.data.ret === 1) {
                        this.total = ret.data.total;
                        this.mockTableData1(ret.data.data);
                        this.page = ret.data.page;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        mockTableData1 (tablelist) {
            let data = [];
            tablelist.forEach((item) => {
                if (item) {
                    switch (item.node_name) {
                    case 1:
                        item.nodename = this.$t(100396);
                        break;
                    case 2:
                        item.nodename = this.$t('8000047');
                        break;
                    case 3:
                        item.nodename = this.$t(100397);
                        break;
                    case 4:
                        item.nodename = this.$t(100398);
                        break;
                    case 5:
                        item.nodename = this.$t(100399);
                        break;
                    case 6:
                        item.nodename = this.$t(400016);
                        break;
                    default:
                        item.nodename = this.$t(600233);
                        break;
                    }
                    item.node_time = moment(item.node_time * 1000).format(
                        'YYYY-MM-DD HH:mm:ss '
                    );
                    data.push(item);
                }
            });
            this.tableData1 = data;
        },
        handleRowChange (currentRow, oldCurrentRow) {
            // 点击之后将某一行的数据添加到obj的对象中
            this.obj = currentRow;
            this.editobj = this.$time.deepClone(currentRow);
        },
        changePage (value) {
            // 改变页码出发函数
            this.page = value;
            // The simulated data is changed directly here, and the actual usage scenario should fetch the data from the server
            this.tableData1 = this.search(this.page, this.pagesize);
        },
        handlePageSize (value) {
            // 改变数据条数触发函数
            this.pagesize = value;
            this.tableData1 = this.search(this.page, this.pagesize);
        },
        add () {
            if (this.machine === 0) {
                this.$Message.error(this.$t('9000416'));
                return false;
            }
            this.addmodal = true;
            this.addobj = {};
        },
        // 获取tree组件的选中子节点
        gettreeNodes (value) {
            // console.log(value)
            this.selectedtreenode = value;
        },
        adddata () {
            var data = this.addobj;
            if (
                data.node_name === undefined ||
        data.node_info === undefined ||
        data.node_cost === undefined ||
        data.node_name === '' ||
        data.node_info === '' ||
        data.node_cost === '' ||
        data.node_cost === 0 ||
        this.machine === 0
            ) {
                this.$Message.error(this.$t('9000136'));
                return;
            }
            data.machine = this.machine;
            this.axios
                .request({
                    url: '/config/machinenode/AddNodeData',
                    data,
                    method: 'post'
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('1'));
                        this.search(1, 10);
                        this.addmodal = false;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        addmodelcancel () {
            this.addmodal = false;
        },
        edit () {
            this.obj = this.$time.deepClone(this.editobj);
            if (this.obj.id === undefined) {
                this.$Message.error(this.$t('1017'));
                return false;
            }

            this.editmodal = true;
        },
        editmodelcancel () {
            // 编辑模态框取消
            this.editmodal = false;
        },
        editdata () {
            // 编辑
            var data = this.obj;
            this.axios
                .request({
                    url: '/config/machinenode/ModifyNodeData',
                    data,
                    method: 'post'
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('1'));
                        this.search(1, 10);
                        this.editmodal = false;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        del () {
            if (JSON.stringify(this.obj) === '{}') {
                this.$Message.error(this.$t('1017'));
                return false;
            } else {
                if (this.obj.node_name < 5) {
                    this.$Message.error(this.$t('960442'));
                    return false;
                }
                this.$Modal.confirm({
                    title: this.$t('1018'),
                    content: '',
                    width: '290px',
                    closable: true,
                    okText: this.$t('1004'),
                    onOk: () => {
                        var params = { id: this.obj.id };
                        axios
                            .request({
                                url: '/config/machinenode/DeleteNodeData',
                                params,
                                method: 'get'
                            })
                            .then((res) => {
                                if (res.data.ret === 1) {
                                    this.$Message.success(this.$t('1058'));
                                    this.page = 1;
                                    this.search();
                                } else {
                                    this.$Message.error(this.$t(res.data.msg));
                                    this.search();
                                }
                            });
                    }
                });
            }
        },
        loadpdf () {
            var target = document.querySelector('#demo');
            html2canvas(target, {
                allowTaint: true,
                dpi: 172,
                background: '#fff'
            }).then(function (canvas) {
                var contentWidth = canvas.width;
                var contentHeight = canvas.height;

                // 一页pdf显示html页面生成的canvas高度;
                var pageHeight = (contentWidth / 592.28) * 841.89;
                // 未生成pdf的html页面高度
                var leftHeight = contentHeight;
                // pdf页面偏移
                var position = 0;
                // html页面生成的canvas在pdf中图片的宽高（a4纸的尺寸[595.28,841.89]）
                var imgWidth = 595.28;
                var imgHeight = (592.28 / contentWidth) * contentHeight;

                var pageData = canvas.toDataURL('image/jpeg', 1.0);
                var pdf = new JsPDF('', 'pt', 'a4');

                // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
                // 当内容未超过pdf一页显示的范围，无需分页
                if (leftHeight < pageHeight) {
                    pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
                } else {
                    while (leftHeight > 0) {
                        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
                        leftHeight -= pageHeight;
                        position -= 841.89;
                        // 避免添加空白页
                        if (leftHeight > 0) {
                            pdf.addPage();
                        }
                    }
                }
                pdf.save('content.pdf');
            });
        }
    }
};
</script>
<style>
.ivu-select-dropdown {
  min-width: 140px;
}
</style>
