<template>
  <!-- 设备状态管理 -->
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div class="filter">
        <label>{{$t('1132')}}：</label>
        <Cascader
          :data="datalevel"
          :value="leveldata"
          trigger="click"
          change-on-select
          class="searchSelect"
          @on-change="getlevel"
        ></Cascader>
      </div>
      <div class="filter">
        <label>{{$t('900908')}}：</label>
        <DatePicker
          type="datetimerange"
          :value="dateTime"
          placeholder
          class="searchInput MaxWidth"
          @on-change="selectdate"
        ></DatePicker>
      </div>
      <div class="filter">
        <label>{{$t('400000')}}：</label>
        <Select v-model="machinestate" clearable class="searchSelect">
          <Option :value="3" v-text="$t('500043')">{{$t('500043')}}</Option>
          <!--空闲-->
          <Option :value="4" v-text="$t('500044')">{{$t('500044')}}</Option>
          <!--报警-->
          <Option :value="0" v-text="$t('500040')">{{$t('500040')}}</Option>
          <!--关机-->
          <Option :value="1" v-text="$t('500041')">{{$t('500041')}}</Option>
          <!--运行-->
          <Option :value="2" v-text="$t('500042')">{{$t('500042')}}</Option>
          <!--手动/调试-->
        </Select>
      </div>
      <div class="filter">
        <label>{{$t('500083')}}：</label>
        <Select v-model="bigsmallspan" clearable class="searchSelect" style="margin-right:10px;">
          <Option :value="2" v-text="$t('200026')">{{$t('200026')}}</Option>
          <Option :value="1" v-text="$t('200027')">{{$t('200027')}}</Option>
        </Select>
        <Input class="searchInput" type="number" v-model="timespan" />
        <span>{{this.$t('1104')}}</span>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="tosearch(0)">{{$t('1001')}}</Button>
        <Button
          type="warning"
          class="twoWord intervalRight"
          icon="ios-build"
          @click="edit()"
        >{{$t('900311')}}</Button>
        <Button
          type="primary"
          class="fourWord"
          icon="md-close-circle"
          @click="clear()"
        >{{$t('1039')}}</Button>
        <Button
          type="primary"
          class="fourWord"
          icon="ios-cloud-download"
          @click="tosearch(1)"
        >{{$t('1007')}}</Button>
      </div>
    </div>
    <div class="divborder newTableDiv">
      <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>
      <Modal
        class="newModalClass"
        :title="$t('900311')"
        v-model="editmodal"
        :styles="{width:'550px'}"
        @on-ok="editdata"
      >
        <div class="modal_body">
          <div>
            <div class="filter">
              <label>{{this.$t('200003')}}：</label>
              <label style="text-align:left;width:300px;">
                <span>{{editobj.sectionID}}</span>
              </label>
            </div>
          </div>
          <div>
            <div class="filter">
              <label>{{this.$t('800271')}}：</label>
              <label style="text-align:left">
                <span>{{editobj.machine_status}}</span>
              </label>
            </div>
          </div>
          <div>
            <div class="filter">
              <label>{{this.$t('1208')}}：</label>
              <label style="text-align:left">
                <span>{{editobj.time_span}}</span>
              </label>
            </div>
          </div>
          <div class="filter">
            <label>{{this.$t('950085')}}：</label>
            <Select
              v-model="parantmode"
              @on-change="modechange"
              clearable
              class="searchSelect MaxWidth"
            >
              <Option
                v-for="item in parentmodes"
                :value="item.id"
                :key="item.id"
              >{{ item.workingmodename }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label>{{this.$t('950049')}}：</label>
            <Select
              v-model="editobj.childmode"
              label-in-value
              clearable
              class="searchSelect MaxWidth"
            >
              <Option
                v-for="item in childmodes"
                :value="item.id"
                :key="item.id"
              >{{ item.workingmodename }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label>{{this.$t('1212')}}：</label>
            <Select v-model="personnel" label-in-value clearable class="searchSelect MaxWidth">
              <Option v-for="item in users" :value="item.id" :key="item.id">{{ item.text }}</Option>
            </Select>
          </div>
          <div class="filter">
            <label>{{this.$t('1030')}}：</label>
            <Input class="searchInput MaxWidth" type="text" id="input1" v-model="editobj.remarks" />
          </div>
        </div>
      </Modal>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import axios from "@/libs/api.request";

export default {
    data() {
        return {
            leveldata: [], // 产线层级集合
            levelid: 0, // 产线层级id
            tableData1: [], // 列表数据
            dateTime: "", // 时间范围
            starttime: "", // 开始时间
            endtime: "", // 结束时间
            machinestate: "", // 统计指标select
            bigsmallspan: "", // 横坐标select
            page: 1,
            pagesize: 10,
            total: 0,
            obj: {},
            treedata1: [],
            datalevel: [],
            allsections: [],
            timespan: "",
            editmodal: false,
            detailobj: {},
            editobj: {},
            parantmode: "",
            parentmodes: [],
            childmode: "",
            childmodes: [],
            personnel: "",
            users: [],
            tableColumns1: [
                {
                    type: "index2",
                    title: this.$t("1008"),
                    key: "xuhao",
                    render: (h, params) => {
                        return h(
                            "span",
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: "60px",
                },
                {
                    title: this.$t("200003"),
                    key: "sectionID",
                },
                {
                    title: this.$t("800271"),
                    key: "machine_status",
                },
                {
                    title: this.$t("1049"),
                    key: "start_time",
                    width: 150,
                },
                {
                    title: this.$t("1050"),
                    key: "end_time",
                    width: 150,
                },
                {
                    title: this.$t("1208"),
                    key: "time_span",
                },
                {
                    title: this.$t("950085"),
                    key: "workModeParnetName",
                    width: 150,
                },
                {
                    title: this.$t("950049"),
                    key: "info",
                    width: 150,
                },
                {
                    title: this.$t("1030"),
                    key: "remarks",
                },
                {
                    title: this.$t("1209"),
                    key: "user",
                },
            ],
        };
    },
    created() {
        this.inittime(); // 初始化
        this.initlevel();
        // 格式化表格样式
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
    },
    methods: {
        inittime() {
            // 时间赋值
            var date = new Date();
            this.dateTime = [
                moment(date.getTime()).format("YYYY-MM-DD ") + "00:00:00",
                moment(date.getTime()).format("YYYY-MM-DD ") + "23:59:59",
            ];
        },
        selectdate(e) {
            var date = new Date();
            let dtEnd = e[1];
            let last_str = dtEnd.split(" ")[1];
            if (last_str == "00:00:00") {
                dtEnd = moment(dtEnd).format("YYYY-MM-DD") + " 23:59:59";
            }
            this.dateTime = [e[0], dtEnd];
        },
        // 产线层级
        initlevel() {
            axios
                .request({
                    url: "config/ProjectLevelSection/GetSectionTree",
                    method: "get",
                })
                .then((res) => {
                    this.levelid = res.data.data[0].value;
                    const arr = [];
                    this.datalevel = res.data.data;
                    arr.push(res.data.data[0].value);
                    this.leveldata = arr;
                    this.search(0);
                });
        },
        // 产线层级选择
        getlevel: function (data) {
            this.levelid = data[data.length - 1];
        },
        tosearch(toexcel) {
            this.page = 1;
            this.pagesize = 10;
            this.search(toexcel);
        },
        search(toexcel) {
            if (this.dateTime === undefined || this.dateTime === "") {
                this.$Message.error(this.$t("800154"));
                return false;
            }

            /*
       *   传递产参数
       *   param   sectionID      int      产线层级
       *   param   errType        int      设备状态
       *   param   big_small      int      持续时长的大于小于
       *   param   big_small_span int      持续时长的 具体分钟
       *   param   startTime      string   开始时间
       *   param   endTime        string   结束时间
       *   param   page           int      当前页
       *   param   pagesize       int      偏移量
       */
            var data = {
                big_small: this.bigsmallspan,
                big_small_span: this.timespan,
                errType: this.machinestate,
                sectionID: this.levelid,
                startTime: moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss"),
                endTime: moment(this.dateTime[1]).format("YYYY-MM-DD HH:mm:ss"),
                page: this.page,
                pagesize: this.pagesize,
                toexcel: toexcel,
            };

            axios
                .request({
                    url: "/cnc/ProjectSectionMachine/GetMachineSateList",
                    data,
                    method: "post",
                })
                .then((res) => {
                    if (toexcel === 0) {
                        this.total = 0;
                        this.tableData1 = [];
                        if (res.data.ret === 1 && res.data.data.length > 0) {
                            this.total = res.data.total;
                            this.mockTableData1(res.data.data);
                        }
                    } else {
                        if (res.data.ret === 0) {
                            this.$Message.error(this.$t("1053"));
                            return false;
                        }
                        if (res.data.data.length > 0) {
                            document.location.href = axios.publicPath + "" + res.data.data;
                        } else {
                            this.$Message.error(this.$t("1053"));
                            return false;
                        }
                    }
                });
        },
        mockTableData1(tablelist) {
            let data = [];
            tablelist.forEach((item) => {
                if (item) {
                    data.push({
                        time_span: this.timechange(item.time_span),
                        machineID: item.machineID,
                        machine_status: this.formatstate(item.machine_status),
                        remarks: item.remarks,
                        sectionID: item.sectionID,
                        id: item.id,
                        start_time: item.start_time,
                        info: item.info,
                        end_time: item.end_time,
                        user: item.user,
                        userId: item.userId,
                        workModeId: item.workModeId,
                        workModeParentId: item.workModeParentId,
                        workModeParnetName: item.workModeParnetName,
                    });
                }
            });
            this.tableData1 = data;
        },
        formatstate(machine_status) {
            if (machine_status === 3) {
                return this.$t("500043");
            } else if (machine_status === 4) {
                return this.$t("500044");
            } else if (machine_status === 0) {
                return this.$t("500040");
            } else if (machine_status === 2) {
                return this.$t("500042");
            } else if (machine_status === 1) {
                return this.$t("500041");
            } else {
                return machine_status;
            }
        },
        handleRowChange(currentRow, oldCurrentRow) {
            this.detailobj = currentRow;
            this.editobj = this.detailobj;
            this.WordMoShi();
            this.getusers();
            this.parantmode = this.detailobj.workModeParentId;
            this.modechange(this.parantmode);
        },
        handlePageSize(value) {
            this.pagesize = value;
            this.tableData1 = this.search(0);
        },
        changePage(value) {
            this.page = value;
            this.tableData1 = this.search(0);
        },
        timechange(num) {
            var str = "";
            if (num > 86400) {
                let d = Math.floor(num / 86400);
                let h = Math.floor((num % 86400) / 3600);
                let m = Math.floor(((num % 86400) % 3600) / 60);
                let s = ((num % 86400) % 3600) % 60;
                str =
          d +
          this.$t("1101") +
          h +
          this.$t("1102") +
          m +
          this.$t("1103") +
          s +
          this.$t("1104");
                return str;
            } else if (num > 3600) {
                let h = Math.floor(num / 3600);
                let m = Math.floor((num % 3600) / 60);
                let s = (num % 24) % 60;
                str = h + this.$t("1102") + m + this.$t("1103") + s + this.$t("1104");
                return str;
            } else if (num > 60) {
                let m = Math.floor(num / 60);
                let s = Math.floor(num % 60);
                str = "" + m + this.$t("1103") + s + this.$t("1104");
                return str;
            } else {
                str = num + this.$t("1104");
                return str;
            }
        },
        clear() {
            this.inittime();
            this.initlevel();
            this.machinestate = "";
            this.bigsmallspan = "";
            this.timespan = "";
            this.tosearch(0);
        },
        edit() {
            if (this.detailobj === undefined || this.detailobj.id === undefined) {
                this.$Message.error(this.$t("1017"));
                return false;
            }

            // this.WordMoShi()
            // this.getusers()

            this.personnel = this.detailobj.userId;
            this.editmodal = true;

            // setTimeout(() => {
            //   this.editobj.childmode = this.detailobj.workModeId
            // }, 200)
        },
        WordMoShi() {
            axios
                .request({
                    url:
            "/cnc/MachineWordingMode/GetParentModesByMachineId?machineID=" +
            this.editobj.machineID,
                    method: "get",
                })
                .then((res) => {
                    this.parentmodes = res.data.data;
                });
        },
        modechange(parent) {
            var data = {
                parentIds: parent || this.parantmode,
            };
            axios
                .request({
                    url: "/cnc/MachineWordingMode/GetSonModesByParents",
                    data,
                    method: "post",
                })
                .then((res) => {
                    this.childmodes = res.data.data;
                })
                .then((res) => {
                    this.editobj.childmode = this.detailobj.workModeId;
                });
        },
        getusers() {
            axios
                .request({
                    url: "/cnc/InformationConfiguration/Getusers",
                    method: "get",
                })
                .then((res) => {
                    this.users = res.data.data;
                });
        },
        editdata() {
            let data = {
                id: this.editobj.id,
                edit_Working_mode_id: this.editobj.childmode,
                edit_personnel_id: this.personnel,
                edit_node: this.editobj.remarks,
                startTime: this.editobj.start_time,
                endTime: this.editobj.end_time,
            };
            axios
                .request({
                    url: "/cnc/ProjectSectionMachine/AppendMode",
                    data,
                    method: "post",
                })
                .then((res) => {
                    this.editmodal = false;
                    this.$Message.info(this.$t("1060"));
                    this.detailobj = {};
                    this.search(0);
                });
        },
    },
};
</script>
<style lang="less" scoped>
.echart-div-list {
  margin-top: 15px;
  border: 0px solid #ddd;
  padding: 15px;
}
.modal_body label {
  width: 100px;
  display: inline-block;
  text-align: right;
}
</style>
