<template>
    <div class="app-container">
        <van-nav-bar title="新增计划" left-text="返回" left-arrow @click-left="$router.go(-1)" />

        

        <van-form @submit="onSubmit">
            <van-field 
                v-model="formData.plan_number"
                name="plan_number"
                label="计划编号"
                placeholder="请输入计划编号"
                clearable
                required
                disabled
            />
              <van-field
                v-model="formData.wind_name"
                name="wind_name"
                label="风场名称"
                placeholder="请输入风场名称"
                clearable
                required
                disabled
            />

            <van-field
                v-model="formData.plan_name"
                name="plan_name"
                label="计划名称"
                placeholder="请输入计划名称"
                clearable
                required
            />
             <van-field
                v-model="formData.fan_model"
                name="fan_model"
                label="风机型号"
                placeholder="请输入部件类型"
                clearable
                required
                @click="showFanModel = true"
            />
            <van-popup v-model="showFanModel" position="bottom">
                <van-picker
                   
                    value-key="name"
                    show-toolbar
                    :columns="fanModel"
                    @confirm="onFanModelConfirm"
                    @cancel="showFanModel = false"
                />
            </van-popup>
           
           
     
            <van-field
                v-model="formData.parts_sign"
                name="parts_sign"
                label="部件类型"
                placeholder="请输入部件类型"
                clearable
                required
                @click="showPart = true"
            />
             <van-popup v-model="showPart" position="bottom">
                <van-picker
                    value-key="name"
                    name="parts_sign"
                    show-toolbar
                    :columns="Part"
                    @confirm="onPartConfirm"
                    @cancel="showPart = false"
                />
            </van-popup>





             <van-field
                v-model="formData.work_sign"
                name="work_sign"
                label="工作位置"
                placeholder="请输入工作位置"
                clearable
                required
                @click="showWorkPage"
            />
             <van-popup v-model="showWork" position="bottom">
                <van-picker
                    value-key="name"
                    name="work_sign"
                    show-toolbar
                    :columns="Work"
                    @confirm="onWorkConfirm"
                    @cancel="showWork = false"
                />
            </van-popup>
            <van-field
                v-model="formData.device_name"
                name="device_name"
                label="螺栓型号"
                placeholder="请输入螺栓型号"
                clearable
            />
            <van-field
                v-model="formData.device_name"
                name="device_name"
                label="螺栓总数"
                placeholder="请输入螺栓总数"
                clearable
            />
            <van-field
                v-model="formData.device_name"
                name="device_name"
                label="紧固模式"
                placeholder="请输入紧固模式"
                clearable
                required
            />
            <van-field
                v-model="formData.device_name"
                name="device_name"
                label="偏移紧固数值"
                placeholder="请输入偏移紧固数值"
                clearable
            />
            <van-field
                v-model="formData.device_name"
                name="device_name"
                label="扭矩"
                placeholder="请输入扭矩"
                clearable
                required
            />
            <van-field
                v-model="formData.device_name"
                name="device_name"
                label="使用状态"
                placeholder="请输入使用状态"
                clearable
            />
            <van-field
                v-model="formData.device_name"
                name="device_name"
                label="备注"
                placeholder="请输入备注"
                clearable
            />

            

            <div style="margin: 6px;">
                <van-button round block type="info" size="small" native-type="submit">新增</van-button>
            </div>

        </van-form>
    </div>
</template>

<script>
import Vue from 'vue';
import wx from 'weixin-js-sdk'
import { Form, Field, Icon, NavBar, Dialog, Button, Popup,Picker } from 'vant';

Vue.use(Form);
Vue.use(Field);
Vue.use(Icon);
Vue.use(NavBar);
Vue.use(Dialog);
Vue.use(Button); 
Vue.use(Popup);
Vue.use(Picker);

export default {
    data() {
        return {
            userid: '',
            openid: '',
            
            formData:{
                plan_number: '',
                plan_name: '',
                wind_name: '',
                fan_model: '',
                parts_sign: '',
                work_sign: '',
                boit_type_sign: '',
                bolt_num: '',
                bias: '',
                tighten_mode: '',
                torque: '',
                status: '',
                info:'',
            },
            imei: '',
            username: '',
            user_no: '',
            userType: '',
            deviceType: '',

            fanModel: [],
            showFanModel: false,
            fanModelObj: '',
            //部件
            Part:[],
            showPart: false,
            PartObj:'',
            //工作位置
            Work: [],
            showWork: false,
            WorkObj: '',
          
        

            wind_id:'',
            rules: {
                imei: [
                    { required: true, message: '请输入设备号' },
                ]
            }
        }
    },
    created() {
        this.userType = localStorage.getItem('userType');
        this.deviceType = localStorage.getItem('deviceType');
        this.userid = localStorage.getItem('userid');
        this.openid = localStorage.getItem('openid');
        this.initdata();
       
    },
    methods: {
        /**
         * 提交
         */
        onSubmit(values) {
            let postData = {
                device_name: values.device_name,
                imei: values.imei,
                userType: this.userType,
                deviceType: this.deviceType,
            }

            if (values.username) {
                postData.username = values.username;
            }
            if (values.user_no) {
                postData.user_no = values.user_no;
            }
           
            this.$http.post('userBindDevice&userid=' + this.userid + '&openid=' + this.openid, JSON.stringify(postData))
                .then(resp => {
                    if (!resp.data.success) {
                        this.$notify(resp.data.message || '绑定失败');
                        return;
                    }
                    this.$notify({
                        type: 'success',
                        message: resp.data.message || '绑定成功',
                    })
                    // 刷新列表
                    this.$router.replace('devices');
                })
        },
    
        getSingleNumber() {
          
            this.$http.get("createPlanId?userid=" + this.userid + '&openid=' + this.openid).then((resp) => {

                if (resp.data.code != 10000) {
                    this.$notify(resp.data.message)
                    return;
                }
                this.formData.plan_number = resp.data.data;  
            });

        },
        //获取风机型号
        getWindModel()
        {
            this.$http.get("getFanModelbyWindId?wind_id=" + this.wind_id + '&openid=' + this.openid).then((resp) => {

                if (resp.data.code != 10000) {
                    this.$notify(resp.data.message)
                    return;
                }
                this.fanModel = resp.data.data;
               
            });


        },

        //提交风场型号
        onPartConfirm(value)
        {   
            console.log(value);
            this.PartObj = value;
            this.formData.parts_sign = value.name;
            this.getWork();
            this.showPart = false;
           
        },


        //提交上传部件
        getPart() {
            let query =
                { type: 1 };
    
            this.$http.post("getParts?openid=" + this.openid, JSON.stringify(query)).then((resp) => {
                if (resp.data.code != 10000) {
                    this.$notify(resp.data.message)
                    return;
                }
                this.Part = resp.data.data;
              
            });

        },
        //获取工作
        getWork() {
           
            let query =
                { type: 2,fan_model:this.fanModelObj.id,part:this.PartObj.id };

            this.$http.post("getParts?openid=" + this.openid, JSON.stringify(query)).then((resp) => {
                if (resp.data.code != 10000) {
                    this.$notify(resp.data.message)
                    return;
                }
                this.Work = resp.data.data;
                
            });

        },
        //确认工作位置
        onWorkConfirm(value)
        {
            this.WorkObj = value;
            this.formData.work_sign = value.name;
            this.showWork = false;
           

        },
        showWorkPage()
        {
            this.showWork = true
        },


        //提交风场型号
        onFanModelConfirm(value) {
            this.formData.fan_model = value.name;
            this.fanModelObj = value;
            this.showFanModel = false;
            this.getWork();
        },



        //初始化数据
        initdata()
        {
            this.getSingleNumber();
            this.formData.wind_name = this.$route.query.wind_name;
            this.wind_id = this.$route.query.wind_id; 
            this.getWindModel();
            this.getPart()

        },

        /**
         * 扫码
         */
        scanCode() {
            let that = this;
            let url = encodeURIComponent(location.href.split('#')[0]);
            // ios 设备只认从公众号菜单首次进入页面的URL
            if (localStorage.getItem('userAgent') == 'ios') {
                let mainUrl = localStorage.getItem('mainUrl');
                url = encodeURIComponent(mainUrl);
            }

            this.$http.get("/getSignaturEtc", { params: { url: url } })
            .then(res => {
                if(!res.data.success){
                    this.$notify( res.data.message);
                    return;
                }
          
                let data = res.data.data;
                    // console.log('resp data',data)
                wx.config({
                    // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    debug: false,
                    // 必填，公众号的唯一标识
                    appId: data.appId,
                    // 必填，生成签名的时间戳
                    timestamp: data.timeStamp,
                    // 必填，生成签名的随机串
                    nonceStr: data.nonceStr,
                    // 必填，签名
                    signature: data.signature,
                    // 必填，需要使用的JS接口列表，所有JS接口列表
                    jsApiList: ['scanQRCode']
                });

                wx.error(function (res) {
                    console.log("出错了：" + res.errMsg);//这个地方的好处就是wx.config配置错误，会弹出窗口哪里错误，然后根据微信文档查询即可。
                });

            })
            .catch(res => {
                console.log(res);
            });


            // 成功时
            wx.ready(function () {

                wx.scanQRCode({
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success: function(res) {
                        var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                        console.log("扫描结果："+result);
                        // window.location.href = result;//因为我这边是扫描后有个链接，然后跳转到该页面

                        that.imei = result;
                    },
                    fail: function(e){
                        console.log('scan fail',e)
                    }
                });

            }); 
        }
    }
}
</script>

<style lang="scss" scoped>

</style>