<template>
    <div class="risk-details">
        <md-scroll-view
                ref="scrollView"
                :bouncing="false"
                :scrolling-x="false"
                :auto-reflow="true"
                @end-reached="$_onEndReached"
        >
            <md-field>
                <md-field-item
                        title="危险源"
                        @click="showDangerSrcSelector"
                        arrow
                        solid
                >
                    <template slot="default" v-if="formData.dangerSrcName == ''"><span
                            style="color: #bab9b9!important;">必选</span></template>
                    <template slot="default" v-else><span>{{formData.dangerSrcName}}</span></template>
                </md-field-item>
                <md-input-item
                        v-model="formData.riskName"
                        title="作业步骤"
                        placeholder="必填"
                ></md-input-item>
                <md-input-item
                        v-model="formData.riskReason"
                        title="危害因素"
                        placeholder="必填"
                ></md-input-item>
                <md-input-item
                        v-model="formData.riskConsequence"
                        title="危害产生的后果"
                        placeholder="必填"
                ></md-input-item>
                <md-input-item
                        v-model="formData.riskCode"
                        title="风险编号"
                        placeholder="必填"
                ></md-input-item>
                <md-field-item
                        title="风险等级"
                        @click="showRiskLevelPopup"
                        arrow
                        solid
                >
                    <template slot="default" v-if="formData.riskLevelText == ''"><span
                            style="color: #bab9b9!important;">必填</span></template>
                    <template slot="default" v-else><span>{{formData.riskLevelText  }}</span></template>
                </md-field-item>
                <md-field-item
                        title="管控层级"
                        arrow
                        solid
                >
                    <template slot="default" v-if="formData.riskCtrlLevelName == ''"><span
                            style="color: #bab9b9!important;">选择风险等级后自动获取</span></template>
                    <template slot="default" v-else><span>{{formData.riskCtrlLevelName  }}</span></template>
                </md-field-item>
                <md-field-item
                        title="管控岗位"
                        @click="showRiskCtrlPositionSelector"
                        arrow
                        solid
                >
                    <template slot="default" v-if="formData.riskCtrlPositionId == ''"><span
                            style="color: #bab9b9!important;">必选</span></template>
                    <template slot="default" v-else><span>{{formData.riskCtrlPositionId|showSelectorText(riskCtrlPositionData)  }}</span>
                    </template>
                </md-field-item>

                <md-input-item
                        v-for="(item,index) in riskMeasureType1"
                        :key="'riskMeasureType1' + index"
                        v-model="riskMeasureType1[index]"
                        title="工程"
                        placeholder="最多输入200字"
                        maxlength="200">
                    <template slot="right">
                        <md-button v-if="index === 0" type="primary" size="small" inline @click="addRiskMeasure(1)">添加
                        </md-button>
                        <md-button v-else type="warning" size="small" inline @click="delRiskMeasure(1,index)">删除
                        </md-button>
                    </template>
                </md-input-item>

                <md-input-item
                        v-for="(item,index) in riskMeasureType2"
                        :key="'riskMeasureType2' + index"
                        v-model="riskMeasureType2[index]"
                        title="管理"
                        placeholder="最多输入200字"
                        maxlength="200">
                    <template slot="right">
                        <md-button v-if="index === 0" type="primary" size="small" inline @click="addRiskMeasure(2)">添加
                        </md-button>
                        <md-button v-else type="warning" size="small" inline @click="delRiskMeasure(2,index)">删除
                        </md-button>
                    </template>
                </md-input-item>

                <md-input-item
                        v-for="(item,index) in riskMeasureType3"
                        :key="'riskMeasureType3' + index"
                        v-model="riskMeasureType3[index]"
                        title="教育"
                        placeholder="最多输入200字"
                        maxlength="200">
                    <template slot="right">
                        <md-button v-if="index === 0" type="primary" size="small" inline @click="addRiskMeasure(3)">添加
                        </md-button>
                        <md-button v-else type="warning" size="small" inline @click="delRiskMeasure(3,index)">删除
                        </md-button>
                    </template>
                </md-input-item>

                <md-input-item
                        v-for="(item,index) in riskMeasureType4"
                        :key="'riskMeasureType4' + index"
                        v-model="riskMeasureType4[index]"
                        title="应急"
                        placeholder="最多输入200字"
                        maxlength="200">
                    <template slot="right">
                        <md-button v-if="index === 0" type="primary" size="small" inline @click="addRiskMeasure(4)">添加
                        </md-button>
                        <md-button v-else type="warning" size="small" inline @click="delRiskMeasure(4,index)">删除
                        </md-button>
                    </template>
                </md-input-item>

                <md-input-item
                        v-for="(item,index) in riskMeasureType5"
                        :key="'riskMeasureType5' + index"
                        v-model="riskMeasureType5[index]"
                        title="个体防护"
                        placeholder="最多输入200字"
                        maxlength="200">
                    <template slot="right">
                        <md-button v-if="index === 0" type="primary" size="small" inline @click="addRiskMeasure(5)">添加
                        </md-button>
                        <md-button v-else type="warning" size="small" inline @click="delRiskMeasure(5,index)">删除
                        </md-button>
                    </template>
                </md-input-item>

                <div class="btn-group">
                    <md-button @click="sendFormData" type="primary" size="small">提交
                    </md-button>
<!--                    <md-button @click="goBack" size="small">返回</md-button>-->
                </div>
            </md-field>
        </md-scroll-view>


        <md-picker
                ref="dangerSrcSelector"
                v-if="dangerSrcData.length > 0"
                v-model="dangerSrcSelectorShow"
                :data="[dangerSrcData]"
                :default-index="pickerDefaultIndex"
                :cols="2"
                is-cascade
                title="危险源"
                @confirm="onDangerSrcSelectorChoose"
        ></md-picker>

        <md-selector
                v-model="lSelectorShow"
                :data="lData"
                max-height="320px"
                title="L"
                large-radius
                @choose="onLSelectorChoose"
        ></md-selector>

        <md-selector
                v-model="eSelectorShow"
                :data="eData"
                max-height="320px"
                title="E"
                large-radius
                @choose="onESelectorChoose"
        ></md-selector>

        <md-selector
                v-model="cSelectorShow"
                :data="cData"
                max-height="320px"
                title="C"
                large-radius
                @choose="onCSelectorChoose"
        ></md-selector>

        <md-selector
                v-model="riskCtrlPositionShow"
                :data="riskCtrlPositionData"
                max-height="320px"
                title="管控岗位"
                large-radius
                multi
                okText="确定"
                cancelText="取消"
                @confirm="onRiskCtrlPositionSelectorChoose"
        ></md-selector>


        <md-popup
                v-model="riskLevelPopupShow"
                position="bottom"
                :mask-closable="false"
        >
            <md-popup-title-bar
                    large-radius
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="riskLevelPopupConfirm"
                    @cancel="riskLevelPopupCancel"
            ></md-popup-title-bar>
            <div class="md-popup-content">
                <md-field>
                    <md-field-item
                            title="风险等级"
                            solid
                    >
                        <template slot="default" v-if="lecData.riskLevelText == ''"><span
                                style="color: #bab9b9!important;">请选择LEC指标</span></template>
                        <template slot="default" v-else><span>{{lecData.riskLevelText}}</span></template>
                    </md-field-item>

                    <md-field-item
                            title="L"
                            @click="showLSelector"
                            arrow
                            solid
                    >
                        <template slot="default" v-if="lecData.lText == ''"><span
                                style="color: #bab9b9!important;">必填</span></template>
                        <template slot="default" v-else><span>{{lecData.lText}}</span></template>
                    </md-field-item>

                    <md-field-item
                            title="E"
                            @click="showESelector"
                            arrow
                            solid
                    >
                        <template slot="default" v-if="lecData.eText == ''"><span
                                style="color: #bab9b9!important;">必填</span></template>
                        <template slot="default" v-else><span>{{lecData.eText}}</span></template>
                    </md-field-item>

                    <md-field-item
                            title="C"
                            @click="showCSelector"
                            arrow
                            solid
                    >
                        <template slot="default" v-if="lecData.cText == ''"><span
                                style="color: #bab9b9!important;">必填</span></template>
                        <template slot="default" v-else><span>{{lecData.cText}}</span></template>
                    </md-field-item>
                </md-field>
            </div>
        </md-popup>
    </div>
</template>

<script>
    import {getDangerSources, getCtrlList, getPositionList, saveRisk} from '@/api/risk';
    import lec from '@/utils/lec'
    import {toTree} from '@/utils/build-tree'
    import {
        TabBar,
        Swiper,
        SwiperItem,
        ScrollView,
        ScrollViewRefresh,
        ScrollViewMore,
        Button,
        InputItem,
        Icon,
        Tag,
        Toast,
        Field,
        FieldItem,
        Selector,
        Picker,
        Popup,
        PopupTitleBar
    } from 'mand-mobile'
    import {mapGetters} from "vuex";

    export default {
        name: "",
        components: {
            [TabBar.name]: TabBar,
            [Field.name]: Field,
            [FieldItem.name]: FieldItem,
            [Selector.name]: Selector,
            [Swiper.name]: Swiper,
            [SwiperItem.name]: SwiperItem,
            [ScrollView.name]: ScrollView,
            [ScrollViewRefresh.name]: ScrollViewRefresh,
            [ScrollViewMore.name]: ScrollViewMore,
            [Button.name]: Button,
            [InputItem.name]: InputItem,
            [Icon.name]: Icon,
            [Tag.name]: Tag,
            [Popup.name]: Popup,
            [PopupTitleBar.name]: PopupTitleBar,
            [Picker.name]: Picker,
        },
        data() {
            return {
                formData: {
                    dangerSrcName: '',  // 危险源名称
                    dangerSrcId: '',  // 危险源Id
                    riskName: '',  // 作业步骤
                    riskReason: '',  // 危害因素
                    riskConsequence: '',  // 危害产生的后果
                    riskCode: '',  // 风险编号
                    riskLevel: '',  // 风险等级
                    riskLevelText: '',  // 风险等级名称
                    riskCtrlLevelId: '',  // 管控层级ID
                    riskCtrlLevelName: '',  // 管控层级名称
                    riskCtrlPositionId: '',  // 管控岗位
                    riskMeasureType1: '',  // 工程     var end = "@#@"; 使用这个关联
                    riskMeasureType2: '',  // 管理
                    riskMeasureType3: '',  // 教育
                    riskMeasureType4: '',  // 应急
                    riskMeasureType5: '',  // 个体防护
                },
                dangerSrcSelectorShow: false,
                dangerSrcData: [],
                riskLevelPopupShow: false,  // 风险等级弹窗

                lData: lec.LAll(),
                eData: lec.EAll(),
                cData: lec.CAll(),
                lecData: {
                    l: "",
                    lText: "",
                    e: "",
                    eText: "",
                    c: "",
                    cText: "",
                    riskLevelText: "",
                    riskLevel: "",
                },
                lSelectorShow: false,
                eSelectorShow: false,
                cSelectorShow: false,

                riskCtrlPositionShow: false,   // 管控层级
                riskCtrlPositionData: [],

                riskMeasureType1: [""],
                riskMeasureType2: [""],
                riskMeasureType3: [""],
                riskMeasureType4: [""],
                riskMeasureType5: [""],

                ctrlListData: [],    //企业管控层级

                pickerDefaultIndex: []
            }
        },
        watch: {
            formData: {
                handler: function (v) {
                    // console.log(v)
                },
                deep: true,
                immediate: true
            }
        },
        computed: {
            ...mapGetters([
                'request_config_aId',
                'request_config_cId',
                'request_config_gId',
                'request_config_baseUrl',
                'request_config_riskPointType'
            ])
        },
        filters: {
            showSelectorText: function (val, dataArr) {
                let valArr = val.split(',');
                let textTextArr = [], temp;
                valArr.forEach((valItem) => {
                    temp = dataArr.filter((dataItem) => {
                        return dataItem.value == valItem;
                    })
                    textTextArr.push(temp[0].text);
                })
                return textTextArr.join(',');
            }
        },
        created() {

        },
        mounted() {
            // this.getDetails()
            if (this.$route.query.fromUrl) {
                this.$store.dispatch('request_config/setBaseUrl', this.$route.query.fromUrl)
            } else {
                this.$store.dispatch('request_config/setBaseUrl', location.host)
            }
            // 所以接口传 aId=294，cId=1
            if (this.$route.query.aId && this.$route.query.cId) {
                this.$store.dispatch('request_config/setReqConfig', {
                    aId: this.$route.query.aId,
                    cId: this.$route.query.cId,
                    riskPointType: this.$route.query.riskPointType,
                })
            } else {
                this.$store.dispatch('request_config/setReqConfig', {
                    aId: '',
                    cId: ''
                })
            }
            if (this.request_config_cId && this.request_config_riskPointType) {
                this.getDangerSourcesData();
                this.getCtrlListData();
                this.getPositionListData();
            }

        },
        methods: {

            /*
            * 获取危险源数据
            * */
            async getDangerSourcesData() {
                await getDangerSources(this.request_config_baseUrl, {
                    cId: this.request_config_cId,
                    riskPointType: this.request_config_riskPointType,
                    limit: 1000
                }).then(response => {
                    const {code, msg, data} = response
                    if (code === 1) {
                        this.dangerSrcData = toTree(data, {
                            name: "label",
                            value: "value",
                            pValue: "pValue"
                        }, {
                            name: "dangerSrcName",
                            value: "dangerSrcId",
                            pValue: "parentDangerSrcId"
                        });
                    }
                    Toast.hide()
                }).catch(error => {
                    console.log(error)
                })
            },
            /*
            * 获取危险源数据
            * */
            async getCtrlListData() {
                await getCtrlList(this.request_config_baseUrl, {
                    cId: this.request_config_cId,
                    limit: 1000
                }).then(response => {
                    const {code, msg, data} = response
                    if (code === 1) {
                        this.ctrlListData = data;
                    }
                    Toast.hide()
                }).catch(error => {
                    console.log(error)
                })
            },
            /*
            * 获取危险源数据
            * */
            async getPositionListData() {
                await getPositionList(this.request_config_baseUrl, {
                    cId: this.request_config_cId,
                    limit: 1000
                }).then(response => {
                    const {code, msg, data} = response
                    if (code === 1) {
                        data.forEach(item => {
                            item.text = item.positionTitle;
                            item.value = item.pId;
                        })
                        this.riskCtrlPositionData = data;
                    }
                    Toast.hide()
                }).catch(error => {
                    console.log(error)
                })
            },

            goBack() {
                this.$router.back()
            },
            /**
             * 提交表单
             * */
            async sendFormData() {
                if (this.formData.dangerSrcId === '' ||
                    this.formData.riskName === '' ||
                    this.formData.riskReason === '' ||
                    this.formData.riskConsequence === '' ||
                    this.formData.riskCode === '' ||
                    this.formData.riskLevel === '' ||
                    this.formData.riskCtrlLevelId === '' ||
                    this.formData.riskCtrlPositionId === ''
                ) {
                    Toast.info('必填项不得为空')
                    return false;
                }
                let endFlag = "@#@";
                this.formData.riskMeasureType1 = this.joinRiskMeasure(this.riskMeasureType1, endFlag);
                this.formData.riskMeasureType2 = this.joinRiskMeasure(this.riskMeasureType2, endFlag);
                this.formData.riskMeasureType3 = this.joinRiskMeasure(this.riskMeasureType3, endFlag);
                this.formData.riskMeasureType4 = this.joinRiskMeasure(this.riskMeasureType4, endFlag);
                this.formData.riskMeasureType5 = this.joinRiskMeasure(this.riskMeasureType5, endFlag);
                this.formData.cId = this.request_config_cId;
                this.formData.aId = this.request_config_aId;
                this.formData.riskPointType = this.request_config_riskPointType;
                Toast.loading('提交中...')
                // this.formData.hazardId = this.$route.query.hazardId
                await saveRisk(this.request_config_baseUrl, this.formData).then(response => {
                    const {code, msg, data} = response
                    if (code === 1) {
                        this.initData();
                    }
                    Toast.hide()
                    Toast.info(msg)
                }).catch(error => {
                    console.log(error)
                })
            },
            initData() {
                this.formData = {
                    dangerSrcName: '',  // 危险源名称
                    dangerSrcId: '',  // 危险源Id
                    riskName: '',  // 作业步骤
                    riskReason: '',  // 危害因素
                    riskConsequence: '',  // 危害产生的后果
                    riskCode: '',  // 风险编号
                    riskLevel: '',  // 风险等级
                    riskLevelText: '',  // 风险等级名称
                    riskCtrlLevelId: '',  // 管控层级ID
                    riskCtrlLevelName: '',  // 管控层级名称
                    riskCtrlPositionId: '',  // 管控岗位
                    riskMeasureType1: '',  // 工程     var end = "@#@"; 使用这个关联
                    riskMeasureType2: '',  // 管理
                    riskMeasureType3: '',  // 教育
                    riskMeasureType4: '',  // 应急
                    riskMeasureType5: '',  // 个体防护
                }
                this.riskMeasureType1 = [""]
                this.riskMeasureType2 = [""]
                this.riskMeasureType3 = [""]
                this.riskMeasureType4 = [""]
                this.riskMeasureType5 = [""]
            },
            joinRiskMeasure(arr, flag) {
                let tempText = "";
                arr.forEach((item) => {
                    if (item !== "") {
                        if (tempText === "") {
                            tempText += item;
                        } else {
                            tempText += flag + item;
                        }
                    }
                })
                return tempText;
            },
            /**
             * RiskMeasure
             **/
            addRiskMeasure(type) {
                switch (type) {
                    case 1:
                        this.riskMeasureType1.push("");
                        break;
                    case 2:
                        this.riskMeasureType2.push("");
                        break;
                    case 3:
                        this.riskMeasureType3.push("");
                        break;
                    case 4:
                        this.riskMeasureType4.push("");
                        break;
                    case 5:
                        this.riskMeasureType5.push("");
                        break;
                }
            },
            /**
             * RiskMeasure
             **/
            delRiskMeasure(type, index) {
                switch (type) {
                    case 1:
                        this.riskMeasureType1.splice(index, 1);
                        break;
                    case 2:
                        this.riskMeasureType2.splice(index, 1);
                        break;
                    case 3:
                        this.riskMeasureType3.splice(index, 1);
                        break;
                    case 4:
                        this.riskMeasureType4.splice(index, 1);
                        break;
                    case 5:
                        this.riskMeasureType5.splice(index, 1);
                        break;
                }
            },

            /**
             * 管控岗位
             * */
            showRiskCtrlPositionSelector() {
                this.riskCtrlPositionShow = true;
            },
            onRiskCtrlPositionSelectorChoose(val) {
                this.formData.riskCtrlPositionId = val.join(',');
            },
            /**
             * lec
             **/
            showLSelector() {
                this.lSelectorShow = true;
            },
            onLSelectorChoose({text, value}) {
                this.lecData.lText = text;
                this.lecData.l = value;
                this.sLecFunction();
            },
            showESelector() {
                this.eSelectorShow = true;
            },
            onESelectorChoose({text, value}) {
                this.lecData.eText = text;
                this.lecData.e = value;
                this.sLecFunction();
            },
            showCSelector() {
                this.cSelectorShow = true;
            },
            onCSelectorChoose({text, value}) {
                this.lecData.cText = text;
                this.lecData.c = value;
                this.sLecFunction();
            },

            sLecFunction() {
                let {lecData} = this;
                if (lecData.l && lecData.e && lecData.c) {
                    let level = 4;
                    level = this.lecFunction(lecData.l, lecData.e, lecData.c);

                    let riskLevelText = "";
                    if (level == 1) {
                        riskLevelText = "重大";
                    } else if (level == 2) {
                        riskLevelText = "较大";
                    } else if (level == 3) {
                        riskLevelText = "一般";
                    } else {
                        riskLevelText = "较低";
                    }
                    this.lecData.riskLevel = level;
                    this.lecData.riskLevelText = riskLevelText;
                }
            },

            lecFunction(l, e, c) {
                var d = l * e * c;
                if (d > 320) {
                    return 1;
                } else if (d > 160) {
                    return 2;
                } else if (d > 70) {
                    return 3;
                } else {
                    return 4;
                }
            },

            /**
             * 风险等级弹窗
             * */
            riskLevelPopupConfirm() {
                this.formData.riskLevel = this.lecData.riskLevel;
                this.formData.riskLevelText = this.lecData.riskLevelText;
                this.riskLevelPopupCancel();
                // TODO 获取管控层级
                this.ctrlListData.forEach((item) => {
                    if (item.riskCtrlLevelValue == this.formData.riskLevel) {
                        this.formData.riskCtrlLevelName = item.riskCtrlLevelTitle;
                        this.formData.riskCtrlLevelId = item.riskCtrlLevelId;
                    }
                })
            },
            riskLevelPopupCancel() {
                this.riskLevelPopupShow = false
                this.lecData = {
                    l: "",
                    lText: "",
                    e: "",
                    eText: "",
                    c: "",
                    cText: "",
                    riskLevelText: "",
                    riskLevel: "",
                }
            },
            showRiskLevelPopup() {
                this.riskLevelPopupShow = true;
            },
            /**
             * 危险源选择
             */
            onDangerSrcSelectorChoose(item) {
                if (item[1]) {
                    this.formData.dangerSrcName = item[1].label;
                    this.formData.dangerSrcId = item[1].value;
                }
            },
            showDangerSrcSelector() {
                this.dangerSrcSelectorShow = true;
                this.pickerDefaultIndex = [0,0]
            },

            // async getDetails() {
            //     await getRiskMeasureListByRiskId({
            //         aId: this.$route.query.aId,
            //         cId: this.$route.query.cId,
            //         riskId: this.$route.query.id,
            //     }).then(res => {
            //         const {code, data, count, limit, page} = res;
            //         if (code === 1) {
            //
            //             if (data.riskMeasureList) {
            //                 let myArr = {
            //                     project: [],
            //                     manage: [],
            //                     education: [],
            //                     emergency: [],
            //                     protection: []
            //                 };
            //                 for (let j = 0; j < data.riskMeasureList.length; j++) {
            //                     // data[i].myRiskMeasure
            //                     if (data.riskMeasureList[j].riskMeasureType == 'project') {
            //                         myArr.project.push(data.riskMeasureList[j]);
            //                     } else if (data.riskMeasureList[j].riskMeasureType == 'manage') {
            //                         myArr.manage.push(data.riskMeasureList[j]);
            //                     } else if (data.riskMeasureList[j].riskMeasureType == 'education') {
            //                         myArr.education.push(data.riskMeasureList[j]);
            //                     } else if (data.riskMeasureList[j].riskMeasureType == 'emergency') {
            //                         myArr.emergency.push(data.riskMeasureList[j]);
            //                     } else {
            //                         myArr.protection.push(data.riskMeasureList[j]);
            //                     }
            //                 }
            //                 data.myRiskMeasure = myArr;
            //             }
            //
            //             this.infoRiskData = data;
            //             console.log(this.infoRiskData)
            //         }
            //     }).catch(err => {
            //     })
            // },
            $_onEndReached() {

            }
        }
    }
</script>

<style scoped lang="scss" type="text/scss">
    .risk-details {
        height: 100vh;

        .md-field-item.is-solid {
            .md-field-item-title {
                width: 2rem !important;
            }
        }

        .md-popup-content {
            background: #FFF;
        }

        .input-group, .btn-group {
            padding: 15px;
        }

        .btn-group {
            display: flex;
        }


    }
</style>
<style>
    .md-field-item.is-solid .md-field-item-title {
        width: 2rem;
        font-size: .24rem;
    }

    .md-field-item-control, .md-input-item-input, .md-input-item-fake {
        font-size: .28rem;
    }

    .md-input-item-input {
        margin-left: -.05rem;
    }

    .md-picker-column-item .column-list .column-item {
        font-size: .28rem;
    }
</style>