<template>
    <div class="app-container">
        <div>
            <el-form :inline="true" :model="formSearch" ref="ruleForm" class="demo-form-inline">
                <el-form-item label="时间:">
                    <el-date-picker
                        v-model="formSearch.time"
                        size="mini"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="取码单号:">
                    <el-input v-model="formSearch.number" size="mini" placeholder="请输入取码单号" clearable maxlength="50"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="mini" icon="el-icon-search" @click="search">查询</el-button>
                </el-form-item>
                <el-form-item class="float-right">
                    <el-button type="danger" size="mini" icon="el-icon-circle-plus-outline" @click="addGetDialog()">创建取码单</el-button>
                </el-form-item>
            </el-form>
            <span class="font-size-16 line-height-2em color-error" style="margin-right:20px;">余码量：{{AllData.sendRemainder}}</span>
            <span class="font-size-16 line-height-2em color-error" style="margin-right:20px;">取码量：{{AllData.totalFetch}}</span>
            <span class="font-size-16 line-height-2em color-error" style="margin-right:20px;">印刷量：{{AllData.totalPrint}}</span>
            <br><br>
        </div>
        <el-table :data="tableData" style="width: 100%" @cell-click="clickRowShowDetail">
            <el-table-column prop="fetchId" label="取码单号"></el-table-column>
            <el-table-column prop="fetchTime" label="日期"></el-table-column>
            <el-table-column prop="fetchCount" label="取码数"></el-table-column>
            <el-table-column prop="status" label="取码单状态" width="150">
                <template slot-scope="scope">
                    <span v-if="scope.row.status == 0" class="color-wait">未生成</span>
                    <span v-else-if="scope.row.status == 1" class="color-send">生成中</span>
                    <span v-else-if="scope.row.status == 2" class="color-success">已生成</span>
                </template>
            </el-table-column>
            <el-table-column prop="fileName" label="防伪码">
                <template slot-scope="scope">
                    <el-button type="text" @click="downLoadFile(scope.row.fetchId)">{{scope.row.fileName}}</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250">
                <template slot-scope="scope">
                    <el-button type="text" size="small" v-if="scope.row.status == 0" @click="addGetDialog(scope.row.fetchId,scope.row.fetchTime)">编辑</el-button>
                    <el-button type="text" size="small" v-if="scope.row.status == 0" @click="confirm(scope.row.fetchId)">生成防伪码印刷文件</el-button>
                    <el-button type="text" size="small" @click="showDetail(scope.row.fetchId)">查看</el-button>
                    <el-button type="text" size="small" v-if="scope.row.status == 0" @click="del(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total,  prev, pager, next, sizes, jumper"
            :total="total">
        </el-pagination>
        <el-dialog title="发码" :visible.sync="dialogDownloadVisible" width="500px" :close-on-click-modal='false'>
            <el-form :model="form" :rules="rules" ref="form">
                <el-form-item label="手机号：" :label-width="formLabelWidth" prop="telPhone" ref="telPhone">
                    <el-input v-model.number="form.telPhone" maxlength="11" autocomplete="off" size="small"></el-input>
                </el-form-item>
                <el-form-item label="短信验证码：" :label-width="formLabelWidth" prop="vCode">
                    <el-input v-model.number="form.vCode" autocomplete="off"  size="small" style="width:110px;margin-right:5px;"></el-input>
                    <el-button type="danger" style="width:100px;" size="small" @click="getSendMessage" :disabled="sendStatus">{{!sendStatus?'获取验证码':timer+'秒'}}</el-button>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" @click="submitForm('form')">保存</el-button>
                <el-button type="info" size="mini" @click="resetForm('form')">取消</el-button>
            </div>
        </el-dialog>
        <el-dialog title="创建取码单" :visible.sync="dialogAddVisible" width="500px" :close-on-click-modal='false'>
            <el-form :model="formAdd" :rules="rulesAdd" ref="formAdd">
                <el-form-item label="取码单编号：" :label-width="formLabelWidth">
                    <span>{{num}}</span>
                </el-form-item>
                <el-form-item label="发码时间：" :label-width="formLabelWidth">
                    <span>{{theGetTime}}</span>
                </el-form-item>
                <el-form-item label="印刷公司：" prop="whitelist_id" :label-width="formLabelWidth">
                    <el-select v-model="formAdd.whitelist_id" placeholder="请选择印刷公司"  size="small">
                        <el-option v-for="(item,index) in whiteList" :key="index" :label="item.companyName" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="取码数量：" prop="fetch_count" :label-width="formLabelWidth">
                    <el-input v-model.number="formAdd.fetch_count" size="small"></el-input>
                </el-form-item>
                <el-form-item label="取码单备注：" prop="summary" :label-width="formLabelWidth">
                    <el-input v-model="formAdd.summary" size="small"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" @click="submitForm('formAdd')">保存</el-button>
                <el-button type="info" size="mini" @click="resetForm('formAdd')">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {
    getFetchList,generateFetch,sendMessage,getDownloadUrl,downFiles,deleteFetchList,addFetchList,updateFetch,getFetchDetail
} from "@/api/get"
import { getWhitelist } from "@/api/user"
import {summaryPortal} from '@/api/status'
import {validatePhone,getDayTime,getDay2} from "@/utils/validate"
export default {
    name: "getGet",
    data() {
        const checkPhoneNum = (rule, value, callback) => {
            if (!validatePhone(value)) {
            return callback(new Error('请输入正确的手机号码'));
            } else {
                callback()
            }
        };
        return {
            BASE_URL:config.API_URL,
            formSearch: {//模糊搜索
                time: '',
                number: '',
            },
            form:{
                telPhone:'',
                vCode:''
            },
            formAdd:{},

            rules: {
                telPhone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator:checkPhoneNum,trigger:"blur"}
                ],
                vCode: [
                    { required: true, message: '请输入短信验证码', trigger: 'blur' }
                ]
            },
            rulesAdd:{
                whitelist_id:[
                    {required: true, message: '请选择公司', trigger: 'change'}
                ],
                fetch_count:[
                    {required: true,type:'number', message: '请输入取码数量', trigger: 'blur'}
                ],
            },
            num:'',
            theGetTime:'',
            AllData:{},
            currentPage: 1,                      //当前页
            pageSize: 10,                        //每页条数
            total: 0,                            //总条数
            tableData: [],                      //表格数据
            formLabelWidth:'120px',
            dialogDownloadVisible:false,
            dialogAddVisible:false,
            sendStatus:false,
            timer:60,
            fetchId:'',
            isAddBtn:true,
            isEdit:false,
            whiteList:[]
        };
    },
    mounted() {
        this.initData()
        this.getSummaryData()
    },
    methods: {
        //搜索查询
        search() {
            this.currentPage = 1
            this.initData()
        },
        //获取用户列表
        initData() {
            const params = {
                pageNo: this.currentPage,
                pageSize: this.pageSize,
                discardId: this.formSearch.number|| null,
                startTime:this.formSearch.time?this.formSearch.time[0] : null,
                endTime:this.formSearch.time?this.formSearch.time[1] : null
            }
            this.isAddBtn = true
            getFetchList(params).then(res => {
                this.tableData = res.data.list
                this.total = res.data.total
                for (let i = 0; i < this.tableData.length; i++) {
                    const element = this.tableData[i];
                    if(element.status != 2) {
                        this.isAddBtn = false
                        break
                    }
                }
            })
        },
        //查询总数
        getSummaryData(){
            summaryPortal().then(res =>{
                this.AllData = res.data
            })
        },
        //获取白名单列表
        getCompanyList(){
            const params = {
                pageNo: 1,
                pageSize: 1000,
            }
            
            getWhitelist(params).then(res => {
                this.whiteList = res.data.list
            })
        },
        downLoadFile(id){
            this.dialogDownloadVisible = true
            this.fetchId = id
        },
        getSendMessage(){
            this.$refs['form'].validateField('telPhone',(valid) => {
                if (valid) {
                    console.log('telPhone error');
                    return false;
                } else {
                    sendMessage({phone:this.form.telPhone+''}).then(res => {
                        this.$message({
                            message: res.msg,
                            type: 'success'
                        });
                        this.timer = 60
                        this.sendStatus = true
                        var flag = setInterval(() =>{
                            if(this.timer == 0)
                            {
                                clearInterval(flag)
                                this.sendStatus = false
                            } else {
                                this.timer--
                            }
                        },1000)
                    })
                }
            });

        },
        del(row){
            this.$confirm('此操作将删除‘'+row.fetchId+'’此取码单, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteFetchList({fetch_id:row.fetchId}).then(res => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.initData()
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: err.code == 200 ? 'success' : 'error'
                    });
                })
                
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });          
            });
        },
        //创建取码单
        addFetch(){
            const params = {
                fetch_time:this.theGetTime,
                fetch_id:this.num,
                list:[this.formAdd]
            }
            addFetchList(params).then(res => {
                this.$message({
                    message: res.msg,
                    type: res.code == 200 ? 'success' : 'error'
                });
                this.resetForm('formAdd')
                this.initData()
            }).catch(err => {
                console.log(err);
            })
        },
        //修改取码单
        upDateData(){
            const params = {
                fetch_time:this.theGetTime,
                fetch_id:this.num,
                list:[this.formAdd]
            }
            updateFetch(params).then(res => {
                this.$message({
                    message: res.msg,
                    type: res.code == 200 ? 'success' : 'error'
                });
                this.resetForm('formAdd')
                this.initData()
            }).catch(err => {
                console.log(err);
            })
        },
        
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
            if (valid) {
                if(formName == 'form') {
                    const param ={
                        fetch_id:this.fetchId,
                        phone:this.form.telPhone+'',
                        verify_code:this.form.vCode+''
                    }
                    getDownloadUrl(param).then(res => {
                        window.location.href = this.BASE_URL + res.data
                        this.dialogDownloadVisible = false
                    })
                } else if (formName == 'formAdd') {
                    if(this.isEdit)
                    {
                        this.upDateData()
                    } else {
                        this.addFetch()
                    }
                }
                
            } else {
                console.log('error submit!!');
                return false;
            }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            if(formName == 'form')
            {
                this.dialogDownloadVisible = false
            } else if (formName == 'formAdd') {
                this.dialogAddVisible = false
            }
        },
        confirm(id){
            this.$confirm('此操作将生成防伪码印刷文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                generateFetch({fetch_id:id}).then(res => {
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    });
                    this.initData()
                }).catch(err => {
                    this.$message({
                        message: err.msg,
                        type: err.code == 200 ? 'success' : 'error'
                    });
                })
                
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });          
            });
        },
        //点击列表一行查看详情
        clickRowShowDetail(row, column, cell, event){
            if(cell.cellIndex == 4 || cell.cellIndex == 5) return
            this.showDetail(row.fetchId)
        },
        //防伪取码详情
        showDetail(id) {
            this.$router.push({name:'getGetDetail',query:{id:id}})
        },
        //点击创建取码单
        addGetDialog(ids = null,times = null){
            if( ids == null && times == null && this.isAddBtn == false)
            {
                this.$alert('当前存在尚未生成取码文件的取码单，请生成取码文件后再创建新的取码单!', '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                    }
                });
                return
            }
            this.getCompanyList()
            if(ids == null && times == null) {
                this.isEdit = false
                
            } else {
                this.isEdit = true
                getFetchDetail({fetch_id:ids}).then(res => {
                    this.formAdd = res.data.fetchDetail[0]
                })
            }
            this.dialogAddVisible = true
            this.num = ids || 'QMD_'+getDay2()+'_'+Math.floor(Math.random()*10000)
            this.theGetTime = times || getDayTime()
            // this.$router.push({name:'addGet',query:{ids:ids,times:times}})
        },
        //每页条数变化
        handleSizeChange(val) {
            this.pageSize = val
            this.initData()
        },
        //当前页变化
        handleCurrentChange(val) {
            this.currentPage = val
            this.initData()
        }

    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.input-with-select {
    float: left;
    top: 10px;
}

.el-input {
    width: 230px;
}
</style>
