<!--
 * @Author: chenlong (陈龙)
 * @Date: 2019-11-06 10:14:38
 * @LastEditors: wf
 * @LastEditTime: 2021-11-19 16:02:33
 * @Description: 系统管理>>>告警管理>>>添加|编辑告警
 -->
<template>
    <div class="system-alarm-type-add" :class="{ 'no-channel': alarmProperty == '1' }">
        <dmp-form
            :cols="cols"
            :data="data"
            :inline="true"
            labelPosition="top"
            :rules="rules"
            :errors="errors"
            ref="form"
            style="width: 800px"
        >
            <template slot="productId">
                <!-- <el-input
                   
                    v-if="params.todo == 'edit'"
                    type="text"
                    v-model="data.productName"
                    placeholder="限30位，汉字、字母、数字或符号"
                    maxlength="30"
                    clearable
                ></el-input> -->
                <el-cascader
                    v-model="data.productId"
                    :options="productOptions"
                    :props="productTypeProps"
                    clearable
                    placeholder=""
                    ref="pcascader"
                    @change="productChange"
                >
                </el-cascader>
            </template>

            <template slot="communityId">
                <el-select v-model="data.communityId">
                    <el-option v-for="(item, index) in communityArr" :key="index" :label="item.communityName" :value="item.id"></el-option>
                </el-select>
            </template>
            <template slot="deviceId">
                <el-select v-model="data.deviceId" placeholder="请选择设备" clearable @change="deviceSelect">
                    <el-option v-for="item in deviceOptions" :key="item.id" :value="item.id" :label="item.deviceName"></el-option>
                </el-select>
            </template>

            <template slot="name">
                <span class="txt" v-if="isReadOnly">{{ data.name }}</span>
                <el-input
                    v-else
                    type="text"
                    v-model="data.name"
                    placeholder="限30位，汉字、字母、数字或符号"
                    maxlength="30"
                    clearable
                ></el-input>
            </template>
            <template slot="desc">
                <span class="txt" v-if="isReadOnly">{{ data.desc }}</span>
                <el-input
                    v-else
                    :disabled="isReadOnly"
                    type="textarea"
                    resize="none"
                    v-model="data.desc"
                    placeholder="输入文字，对该告警进行说明或描述"
                    :rows="3"
                    show-word-limit
                    minlength="0"
                    maxlength="100"
                ></el-input>
            </template>

            <template slot="alarmRuleList">
                <div class="dmp-table_alarm">
                    <div class="lixian_class" v-if="alarmCategory == 1">
                        <el-form-item slot="row" class="tip-info" label="测点" prop="measuringCode">
                            <el-select v-model="measuringCode" placeholder="请选择测点" clearable @change="measureSelect">
                                <el-option v-for="item in measureOptions" :key="item.id" :value="item.id" :label="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-table class="avg_table" :data="data.rules" stripe="true">
                            <el-table-column label="运算符" align="left">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'rules.' + scope.$index + '.operator'" :rules="rules['rules.operator']">
                                        <span class="txt" v-if="isReadOnly">{{ scope.row.operator }}</span>
                                        <el-select
                                            v-else
                                            v-model="scope.row.operator"
                                            placeholder=""
                                            @change="validateKey('rules.' + scope.$index + '.operator', scope.row.operator)"
                                            :disabled="scope.row.measuringDataType == 1"
                                            clearable
                                        >
                                            <el-option
                                                v-for="item in operatoroptions"
                                                :key="item.id"
                                                :value="item.id"
                                                :label="item.name"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="条件值" align="left">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'rules.' + scope.$index + '.value'" :rules="rules['rules.value']">
                                        <template v-if="scope.row.measuringDataType == 1">
                                            <span class="txt" v-if="isReadOnly">{{
                                                toStrById(dictList, scope.row.value, 'specsName', 'specsValue')
                                            }}</span>
                                            <el-select
                                                v-else
                                                v-model="scope.row.value"
                                                @change="validateKey('rules.' + scope.$index + '.value', scope.row.value)"
                                                placeholder=""
                                                clearable
                                            >
                                                <el-option
                                                    v-for="item in dictList"
                                                    :key="item.specsValue"
                                                    :value="item.specsValue"
                                                    :label="item.specsName"
                                                ></el-option>
                                            </el-select>
                                        </template>
                                        <template v-else>
                                            <span class="txt" v-if="isReadOnly">{{ scope.row.value }}</span>
                                            <el-input
                                                v-else
                                                v-model.trim="scope.row.value"
                                                :disabled="!scope.row.operator"
                                                @blur="validateKey('rules.' + scope.$index + '.value', scope.row.value)"
                                                maxlength="128"
                                                placeholder="数字"
                                                clearable
                                            ></el-input>
                                        </template>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="条件关系" align="left">
                                <template slot-scope="scope">
                                    <el-form-item :prop="'rules.' + scope.$index + '.relation'" :rules="rules['rules.relation']">
                                        <span class="txt" v-if="isReadOnly">{{ scope.row.relation }}</span>
                                        <!-- :disabled="scope.$index == 0" -->
                                        <el-select
                                            v-else
                                            v-model="scope.row.relation"
                                            @change="validateKey('rules.' + scope.$index + '.relation', scope.row.relation)"
                                            placeholder=""
                                        >
                                            <el-option
                                                v-for="item in relationOptions"
                                                :key="item.id"
                                                :value="item.id"
                                                :label="item.name"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" align="left">
                                <template slot-scope="scope">
                                    <span>{{ scope.row.measuringUnit || '-' }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column v-if="!isReadOnly" label="操作">
                                <template slot-scope="scope">
                                    <!-- && !scope.row.measuringCode v-if="!(scope.$index == 0)"-->
                                    <i class="icon-del-alarm" title="删除" v-if="!(scope.$index == 0)" @click="delRule(scope.$index)"></i>
                                    <i
                                        class="icon-add-alarm"
                                        title="添加"
                                        v-if="scope.$index == data.rules.length - 1 && measuringCode"
                                        @click="addRule(scope.$index)"
                                    ></i>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <el-table v-else :data="data.rules" stripe="true">
                        <el-table-column label="运算符" align="left">
                            <template slot-scope="scope">
                                <el-form-item :prop="'rules.' + scope.$index + '.operator'" :rules="rules['rules.operator']">
                                    <span class="txt" v-if="isReadOnly">{{ scope.row.operator }}</span>
                                    <el-select
                                        v-else
                                        v-model="scope.row.operator"
                                        placeholder=""
                                        @change="validateKey('rules.' + scope.$index + '.operator', scope.row.operator)"
                                        :disabled="scope.row.measuringDataType == 1"
                                        @clear="clearOperate(scope.$index)"
                                        clearable
                                    >
                                        <el-option
                                            v-for="item in operatoroptions"
                                            :key="item.id"
                                            :value="item.id"
                                            :label="item.name"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="条件值" align="left">
                            <template slot-scope="scope">
                                <el-form-item :prop="'rules.' + scope.$index + '.value'" :rules="rules['rules.value']">
                                    <template v-if="scope.row.measuringDataType == 1">
                                        <span class="txt" v-if="isReadOnly">{{
                                            toStrById(dictList, scope.row.value, 'specsName', 'specsValue')
                                        }}</span>
                                        <el-select
                                            v-else
                                            v-model="scope.row.value"
                                            @change="validateKey('rules.' + scope.$index + '.value', scope.row.value)"
                                            placeholder=""
                                            clearable
                                        >
                                            <el-option
                                                v-for="item in dictList"
                                                :key="item.specsValue"
                                                :value="item.specsValue"
                                                :label="item.specsName"
                                            ></el-option>
                                        </el-select>
                                    </template>
                                    <template v-else>
                                        <span class="txt" v-if="isReadOnly">{{ scope.row.value }}</span>
                                        <el-input
                                            v-else
                                            v-model.trim="scope.row.value"
                                            :disabled="!scope.row.operator"
                                            @blur="validateKey('rules.' + scope.$index + '.value', scope.row.value)"
                                            maxlength="128"
                                            placeholder="数字"
                                            clearable
                                        ></el-input>
                                        <span class="txt time_txt">分钟</span>
                                    </template>
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </template>
            <template slot="timeSet">
                <div class="time_set">
                    <div class="time_content" v-for="(item, index) in data.timeList" :key="index">
                        <div class="timeduring">
                            <div class="time_picker">
                                <el-form-item :prop="'timeList.' + index + '.startTime'" :rules="rules.startTime">
                                    <el-time-picker
                                        value-format="HH:mm:ss"
                                        v-model="item.startTime"
                                        placeholder="开始时间"
                                        class="time_start"
                                    >
                                    </el-time-picker>
                                </el-form-item>
                                <el-form-item class="end_time" :prop="'timeList.' + index + '.endTime'" :rules="rules.endTime">
                                    <span style="margin: 5px">~</span>
                                    <el-time-picker value-format="HH:mm:ss" v-model="item.endTime" placeholder="结束时间" class="time_end">
                                    </el-time-picker>
                                </el-form-item>
                            </div>
                            <div class="add_img">
                                <i class="icon_add" @click="addTime"></i>
                                <i class="icon_delete" v-if="index != 0" @click="deleteTime(index)"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
            <template slot="dayset">
                <el-form-item>
                    <div class="time_sys">
                        <el-switch v-model="checkFlag" width="45" active-color="#0eaeff" inactive-color="#d8d8d8" @change="changeSwitch">
                        </el-switch>
                        <span class="every_day">每天</span>
                        <ul v-if="!checkFlag" class="ul-time">
                            <li v-for="(item, index) in dayOption" :key="index" style="cursor: pointer">
                                <el-checkbox v-model="item.checked" @change="onChange($event)">{{ item.name }}</el-checkbox>
                            </li>
                        </ul>
                    </div>
                </el-form-item>
            </template>
        </dmp-form>
    </div>
</template>

<script>
import { bodyContent, addCols, operatorOptions, relationOptions, alarmCategoryOptions, toStrById } from './util';
export default {
    props: {
        params: Object
    },
    data() {
        const _selft = this;
        return {
            data: JSON.parse(JSON.stringify(bodyContent)),
            alarmCategory: '1',
            measuringCode: '',
            cols: [],
            measureOptions: [],
            dictList: [],
            rules: {
                communityId:this.$valid.selectRequired('社区'),
                productId: this.$valid.selectRequired('产品'),
                name: [this.$valid.inputRequired('告警名称'), this.$valid.lengthRange(0, 30)],
                // measuringCode: this.$valid.selectRequired('测点'),
                measuringCode: this.$valid.custome({
                    validator(rule, value, cb) {
                        let vv = _selft.measuringCode;
                        const rl = rule;
                        if (!vv) {
                            rl.message = '请选择测点值';
                            cb(new Error());
                        } else {
                            cb();
                        }
                    }
                }),
                startTime: this.$valid.custome({
                    validator(rule, value, cb) {
                        const rl = rule;
                        let regExp = /^[0-2][0-9]\:[0-5][0-9]\:[0-5][0-9]$/;
                        if (!value) {
                            rl.message = '请选择时间';
                            cb(new Error());
                        } else if (!regExp.test(value)) {
                            rl.message = '时间格式错误';
                            cb(new Error());
                        } else {
                            cb();
                        }
                    }
                }),
                endTime: this.$valid.custome({
                    validator(rule, value, cb) {
                        const rl = rule;
                        let regExp = /^[0-2][0-9]\:[0-5][0-9]\:[0-5][0-9]$/;
                        if (!value) {
                            rl.message = '请选择时间';
                            cb(new Error());
                        } else if (!regExp.test(value)) {
                            rl.message = '时间格式错误';
                            cb(new Error());
                        } else {
                            cb();
                        }
                    }
                })
                // alarmCategory: this.$valid.selectRequired('告警分类')
            },
            errors: {},
            cascaderProps: { value: 'id', expandTrigger: 'hover' },
            alarmCategoryOptions,
            measuringOptions: [],
            operatoroptions: operatorOptions,
            copyoperatorOptions: [],
            relationOptions,
            productIds: [],
            alarmProperty: '2',
            productTypeProps: {
                value: 'id', // 唯一标识
                label: 'label', // 标签显示
                children: 'children' // 子级
            },
            deviceOptions: [],
            productOptions: [],
            isReadOnly: false,
            toStrById,
            dayOption: [
                { id: 2, name: '周一', checked: false },
                { id: 3, name: '周二', checked: false },
                { id: 4, name: '周三', checked: false },
                { id: 5, name: '周四', checked: false },
                { id: 6, name: '周五', checked: false },
                { id: 7, name: '周六', checked: false },
                { id: 1, name: '周日', checked: false }
            ],
            checkFlag: true
        };
    },
    computed: {
        communityArr() {
            return this.$store.getters['getAreaSelect'];
        }
    },
    methods: {
        getDeviceOptions(id) {
            this.$http.get('/sc-community/device/findByProduct?id=' + id).then(({ data }) => {
                this.deviceOptions = data;
            });
        },
        getMeasurePointOptions(id) {
            let params = { deviceTypeId: id };
            this.$http.get('/sc-community/attributes/listBydeviceTypeId', params).then(({ data }) => {
                this.measureOptions = data;
            });
        },
        deviceSelect(value) {
            let item = _.find(this.deviceOptions, (it) => it.id == value);
            this.$set(this.data, 'iotDeviceId', item.iotDeviceId || '');
        },
        measureSelect(value) {
            let results = {};
            this.measureOptions.map((item, index) => {
                if (item.id == value) {
                    return (results = item);
                }
            });
            this.$set(this.data, 'attributeId', results.id);
            this.$set(this.data, 'identifier', results.identifier);
            this.getOperator(results.id || '');
            if (this.data.rules.length > 1) {
                this.data.rules.splice(1, this.data.rules.length);
            }
            this.data.rules[0].measuringCode = this.measuringCode;
            this.data.rules[0].operator = '';
            this.data.rules[0].relation = 'AND';
            this.data.rules[0].value = '';
            if (!_.isEmpty(results)) {
                Object.assign(this.rules, {
                    'rules.operator': this.$valid.selectRequired('运算符'),
                    'rules.value': this.$valid.selectRequired('条件值'),
                    'rules.relation': this.$valid.selectRequired('条件关系')
                });
            } else if (this.data.rules.length == 1) {
                this.$refs.form.$refs.form.clearValidate(['rules.0.operator', 'rules.0.value', 'rules.0.relation']);
                delete this.rules['rules.operator'];
                delete this.rules['rules.value'];
                delete this.rules['rules.relation'];
            }
        },
        getOperator(attributeId) {
            let _self = this;
            _self.$http.get(`/sc-community/attributes/specs/list?attributeId=${attributeId}`).then(({ status, data = [] }) => {
                if (status == 0) {
                    _self.dictList.splice(0, _self.dictList.length);
                    if (data.length > 0) {
                        data.map((it) => {
                            _self.dictList.push(it);
                        });
                        if (_self.dictList.length > 0) {
                            // eslint-disable-next-line no-param-reassign
                            _self.data.rules.map((it) => {
                                it.operator = '=';
                            });
                            this.rules['rules.value'] = this.$valid.selectRequired('条件值');
                        } else {
                            this.rules['rules.value'] = this.$valid.custome({
                                validator(rule, value, cb) {
                                    const rl = rule;
                                    if (value) {
                                        if (value >= -99999999 && value <= 99999999) {
                                            cb();
                                        } else {
                                            rl.message = '您输入格式有误，请重新输入';
                                            cb(new Error());
                                        }
                                    } else {
                                        rl.message = '请输入条件值';
                                        cb(new Error());
                                    }
                                }
                            });
                        }
                    } else {
                        _self.dictList = _self.dictList.length > 0 ? _self.dictList.splice(0, _self.dictList.length) : [];
                    }
                    this.data.rules.map((ita) => {
                        if (_self.dictList.length > 0) {
                            ita.measuringDataType = '1';
                            ita.operator = '=';
                        } else {
                            ita.measuringDataType = '2';
                        }
                    });
                }
            });
        },
        addTime() {
            let _self = this;
            this.$nextTick(() => {
                _self.data.timeList.push({ startTime: '00:00:00', endTime: '23:59:59' });
            });
        },
        deleteTime(index) {
            let _self = this;
            this.$nextTick(() => {
                _self.data.timeList.splice(index, 1);
            });
        },
        changeSwitch() {
            let xx = this.checkFlag;
        },
        onChange(value) {},
        validateKey(key, val) {
            val && this.$refs.form.$refs.form.clearValidate([key]);
        },
        measuringChange(id, row) {
            const obj = _.find(this.measuringOptions, (v) => v.measuringCode == id);
            Object.assign(row, {
                operator: '',
                value: '',
                relation: 'AND',
                measuringUnit: ''
            });
            if (!_.isEmpty(obj)) {
                Object.assign(this.rules, {
                    'rules[0].measuringCode': this.$valid.selectRequired('测点'),
                    'rules.operator': this.$valid.selectRequired('运算符'),
                    'rules.value': this.$valid.selectRequired('条件值'),
                    'rules.relation': this.$valid.selectRequired('条件关系')
                });
                const { measuringDataType, measuringUnit, dictList } = obj;
                Object.assign(row, {
                    measuringDataType,
                    measuringUnit,
                    dictList
                });
                if (measuringDataType == 1) {
                    // eslint-disable-next-line no-param-reassign
                    row.operator = '=';
                    this.rules['rules.value'] = this.$valid.selectRequired('条件值');
                } else {
                    this.rules['rules.value'] = this.$valid.custome({
                        validator(rule, value, cb) {
                            const rl = rule;
                            if (value) {
                                if (value >= -99999999 && value <= 99999999) {
                                    cb();
                                } else {
                                    rl.message = '您输入格式有误，请重新输入';
                                    cb(new Error());
                                }
                            } else {
                                rl.message = '请输入条件值';
                                cb(new Error());
                            }
                        }
                    });
                }
            } else if (this.data.rules.length == 1) {
                this.$refs.form.$refs.form.clearValidate(['rules.0.operator', 'rules.0.value', 'rules.0.relation']);
                delete this.rules['rules.measuringCode'];
                delete this.rules['rules.operator'];
                delete this.rules['rules.value'];
                delete this.rules['rules.relation'];
            }
        },
        getMeasuring(id, isEdit) {
            this.$http.get(`/zoniot-rmcp-web/alarmRule/getRuleMeasuringList?deviceTypeId=${id}`).then(({ status, data = [] }) => {
                if (status == 0) {
                    this.measuringOptions = data;
                    if (isEdit) {
                        const rules = this.data.rules.length
                            ? JSON.parse(JSON.stringify(this.data.rules))
                            : [
                                  {
                                      id: '',
                                      measuringCode: '',
                                      measuringDataType: '',
                                      operator: '',
                                      value: '',
                                      relation: 'AND',
                                      measuringUnit: ''
                                  }
                              ];
                        _.each(rules, (v) => {
                            const obj = _.find(data, (m) => m.measuringCode == v.measuringCode);
                            // eslint-disable-next-line no-param-reassign
                            v.dictList = _.isEmpty(obj) ? [] : obj.dictList;
                        });
                        const params = JSON.parse(JSON.stringify(this.params.data));
                        Object.assign(this.data, params, { rules });
                    }
                }
            });
        },
        productChange(e) {
            let  lat = _.last(e)
            this.measuringOptions = [];
            this.data.productId = e;
            this.data.deviceId = '';
            this.getDeviceOptions(lat);
            this.getMeasurePointOptions(lat);
            let rec = this.getCascaderObj(lat, this.productOptions);
            this.data.iotProductId = rec.iotId || '';
        },
        delRule(index) {
            this.data.rules.splice(index, 1);
            if (this.data.rules.length == 0) {
                this.data.rules = [
                    {
                        id: '',
                        measuringCode: '',
                        measuringDataType: this.dictList.length > 0 ? '1' : '2',
                        operator: '',
                        value: '',
                        relation: 'AND',
                        measuringUnit: ''
                    }
                ];
            }
            if (this.data.rules[0].relation != 'AND') {
                this.data.rules[0].relation = 'AND';
            }
        },
        addRule(index) {
            const props = [`rules.${index}.operator`, `rules.${index}.value`, `rules.${index}.relation`];
            let count = props.length;
            this.$refs.form.$refs.form.validateField(props, (errorMessage) => {
                if (!errorMessage) {
                    count -= 1;
                }
                if (count == 0 && this.data.rules[0].measuringCode) {
                    this.data.rules.push({
                        id: '',
                        measuringCode: this.data.rules[0].measuringCode || '',
                        measuringDataType: this.dictList.length > 0 ? '1' : '2',
                        operator: this.dictList.length > 0 ? '=' : '',
                        value: '',
                        relation: 'AND',
                        measuringUnit: ''
                    });
                } else {
                }
            });
        },
        reset() {
            const dataBak = JSON.parse(JSON.stringify(this.data));
            this.data = JSON.parse(JSON.stringify(bodyContent));
            if (this.params.todo == 'add') {
                this.productIds = [];
            } else {
                this.data.id = dataBak.id;
                this.data.productId = dataBak.productId;
                this.data.alarmProperty = dataBak.alarmProperty;
            }
            this.$refs.form.resetFields();
        },
        //深拷贝
        deepClone(obj) {
            if (typeof obj !== 'object') return;
            let newObj = obj instanceof Array ? [] : {};
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    newObj[key] = typeof obj[key] === 'object' ? this.deepClone(obj[key]) : obj[key];
                }
            }
            return newObj;
        },
        getQueryInfo(id) {
            if (this.params && this.params.todo == 'edit') {
                this.$http.get(`/sc-community/system/alarmType/findAlarmTypeById?id=${id}`).then(({ data }) => {
                    this.data = Object.assign(this.data, data);
                    this.data.productId = [null, null, data.productId + ''];
                    this.getDeviceOptions(data.productId);
                    this.getMeasurePointOptions(data.productId);
                    this.measuringCode = this.data.rules[0].measuringCode ? this.data.rules[0].measuringCode : '';
                    this.getOperator(this.data.attributeId);
                    this.setDaysAndTimes(data.days, data.times);
                });
            }
        },
        clearOperate(index) {
            this.data.rules[index].value = '';
        },
        getCascaderObj(val, opt) {
            if (!(opt && opt.length)) {
                return '';
            }
            let res = '';
            const forFn = (opt, val) => {
                for (let i = 0; i < opt.length; i += 1) {
                    const item = opt[i];
                    if (item.id == val) {
                        res = item;
                        break;
                    }
                    if (item.children) {
                        forFn(item.children, val);
                    }
                }
            };
            forFn(opt, val);
            return res;
        },
        setDaysAndTimes(days = '', times = '-') {
            let dayarr = days.split(',');
            if (dayarr && dayarr.length > 0) {
                if (dayarr[0] == 8) {
                    this.checkFlag = true;
                } else {
                    this.checkFlag = false;
                    this.dayOption.map((it) => {
                        if (dayarr.includes(it.id.toString())) {
                            it.checked = true;
                        }
                    });
                }
            }
            let timearr = times.split(',');
            if (timearr && timearr.length > 0) {
                timearr.map((ita, idx) => {
                    let timespan = ita.split('-');
                    if (timespan && timespan.length > 1) {
                        let newitem = null;
                        if (idx == 0) {
                            this.data.timeList[0].startTime = timespan[0];
                            this.data.timeList[0].endTime = timespan[1];
                        } else {
                            newitem = { startTime: timespan[0], endTime: timespan[1] };
                            this.data.timeList.push(newitem);
                        }
                    } else {
                        this.data.timeList.push({ startTime: '', endTime: '' });
                    }
                });
            }
        },
        submit() {
            let _self = this;
            new Promise((res) => {
                // resolve();
                this.$refs.form.validate(res);
            })
                .then(() => {
                    let url = '/sc-community/system/alarmType/add',
                        method = 'post';
                    if (this.params.todo == 'edit') {
                        url = '/sc-community/system/alarmType/edit';
                        method = 'post';
                    }
                    let times = '';
                    this.data.timeList.map((item, index) => {
                        if (index == _self.data.timeList.length - 1) {
                            times += `${item.startTime}-${item.endTime}`;
                        } else {
                            times += `${item.startTime}-${item.endTime},`;
                        }
                    });
                    let days = '';
                    if (!this.checkFlag) {
                        this.dayOption.map((itemarr, idx) => {
                            if (itemarr.checked) {
                                days += itemarr.id + ',';
                            }
                        });
                        days = days.slice(0, days.length - 1);
                    } else {
                        days = '8';
                    }
                    let newdata = Object.assign(this.data, { days }, { times });
                    const params = JSON.parse(JSON.stringify(newdata));
                    params.productId = _.last(params.productId);
                    const rules = [];
                    // _.each(params.rules, (v) => {
                    //   if (v.measuringCode) {
                    //     rules.push(v);
                    //   }
                    // })
                    // params.rules = rules;
                    _self.data.rules.map((it, index) => {
                        if (index >= 1) {
                            it.measuringCode = _self.data.rules[0].measuringCode;
                        }
                    });

                    const $loading = this.$loading();
                    this.$http[method](url, params)
                        .then(({ status, msg }) => {
                            if (status == 0) {
                                this.$message.success(msg);
                                this.params.callback();
                                this.$emit('close');
                            } else if (status === 500017) {
                                this.$set(this.errors, 'name', msg);
                            } else {
                                this.$message.error(msg);
                            }
                            $loading.close();
                        })
                        .catch(() => {
                            this.$loading.close();
                        });
                })
                .catch(() => {});
        }
    },
    created() {
        this.copyoperatorOptions = operatorOptions.slice();
        this.alarmCategory = this.params.alarmCategory;
        // this.deviceOptions=this.params.deviceOptions;
        this.productOptions = this.params.productOptions;
        if (this.alarmCategory == '2') {
            let newaddCols = addCols[0].slice(0, 5);
            this.cols = [newaddCols];
        } else {
            this.cols = addCols;
        }

        if ((this.params && this.params.todo == 'edit') || this.params.todo == 'view') {
            this.getQueryInfo(this.params.data.id);
            this.$set(this.data, 'name', this.params.data.alarmName);

            //给日期和星期赋值this.params.data.days,this.params.data.times
            this.isReadOnly = this.params.todo == 'view';
        }
        this.$set(this.data, 'alarmCategory', this.alarmCategory);
        this.$set(this.data, 'sceneType', '3');
    }
};
</script>
<style lang="scss" scoped>
@import './style.scss';
.icon-del-alarm {
    display: inline-block;
    width: 16px;
    height: 16px;
    cursor: pointer;
    background: url('~@assets/img/menuicon/icon-del.png') no-repeat center;
    background-size: 100% 100%;
    margin-right: 10px;
}
.icon-add-alarm {
    display: inline-block;
    width: 16px;
    height: 16px;
    cursor: pointer;
    background: url('~@assets/img/menuicon/icon-add.png') no-repeat center;
    background-size: 100% 100%;
}
.time_picker /deep/ .el-form-item {
    margin-bottom: 0px;
    .el-form-item__error {
        padding-top: 7px;
    }
    &.end_time {
        .el-form-item__error {
            left: 40px !important;
        }
    }
}
</style>

