<template>
    <customer-navBar-layout>
        <template #navBar>
            <van-nav-bar v-if="showCheck"
                         :title="$route.meta.title"
                         right-text="取消"
                         left-arrow
                         @click-left="_back"
                         @click-right="_hideCheck">
            </van-nav-bar>
            <van-nav-bar
                    v-else
                    :title="$route.meta.title"
                    right-text="添加"
                    left-arrow
                    @click-left="_back"
                    @click-right="_add"
            ></van-nav-bar>
        </template>
        <template #content>
            <search-bar label="抽样单编号" ref="searchBar"
                        highSearch @search="_search" @high-search="_highSearch"
                        @clear-high="_clearHigh">
                <template #highSearch>
                    <van-field v-model="formObj.samplingNum" label="抽样单编号" placeholder="请输入抽样单编号"></van-field>
                    <van-field v-model="formObj.placeName" label="地点" placeholder="请输入地点"></van-field>
                    <van-field v-model="formObj.shelfName" label="货架" placeholder="请输入货架"></van-field>
                </template>
            </search-bar>
            <div class="layout-cont-sh" :class="{'layout-cont-sh-btn':showCheck}">
                <!--下拉刷新  https://vant-contrib.gitee.io/vant/#/zh-CN/pull-refresh-->
                <van-pull-refresh v-model="refreshing" @refresh="_refresh">
                    <!--上拉加载 https://vant-contrib.gitee.io/vant/#/zh-CN/list-->
                    <van-list
                            v-model="loading"
                            :finished="finished"
                            finished-text="没有更多了"
                            @load="_load">
                        <van-checkbox-group v-model="checkListValue" ref="checkboxGroup">
                            <van-swipe-cell v-for="item in resultList" :key="item.id">
                                <div class="result-item" @click="_tapItem(item)" v-touch:longtap="_longtapHandler">
                                    <div style="width: 100%;display: flex;justify-content: space-between;border-bottom: 1px solid #eeeeee">
                                        <div style="display: flex">
                                            <div style="margin-right: 20px" v-if="showCheck">
                                                <van-checkbox :name="item.id" shape="square"></van-checkbox>
                                            </div>
                                            <div>抽样单编号：{{item.samplingNum}}</div>
                                        </div>
                                        <div @click.stop="_goFile(item.id)">
                                            <img src="../../assets/file-nav.png" style="width: 20px">
                                        </div>
                                    </div>
                                    <div>抽样日期：{{item.samplingDate?$dateformat(item.samplingDate,'yyyy-mm-dd'):''}}</div>
                                    <div>生产者名称：{{item.proName}}</div>
                                    <div>样品名称：{{item.sampleName}}</div>
                                    <div>被抽样单位名称：{{item.testedName}}</div>
                                    <div>地点：{{item.placeName}}</div>
                                    <div>货架：{{item.shelfName}}</div>
                                </div>
                                <template #right>
                                    <van-button square type="info" text="编辑" class="swipe-cell-btn"
                                                @click="_edit(item)"></van-button>
                                    <van-button square type="primary" text="打印" class="swipe-cell-btn"
                                                @click="_print(item)"></van-button>
                                    <van-button square type="danger" text="删除" class="swipe-cell-btn"
                                                @click="_del([item.id])"></van-button>
                                </template>
                            </van-swipe-cell>
                        </van-checkbox-group>
                    </van-list>
                </van-pull-refresh>
            </div>
            <div class="bottom-btn" v-if="showCheck">
                <van-button square block @click="_checkAll">{{checkAll?'取消全选':'全选'}}</van-button>
                <van-button square block type="danger" @click="_del(checkListValue)">删除</van-button>
            </div>
        </template>
        <SelectShelves ref="shelvesSelect" @on-select="_shelvesResult"></SelectShelves>
    </customer-navBar-layout>
</template>

<script>
    import SelectShelves from './components/SelectShelves'
    import {samplingSummary} from '../../api'

    export default {
        name: "SamplingList",
        components: {
            SelectShelves
        },
        data() {
            return {
                formObj: {
                    samplingNum: '',
                    placeName: '',
                    shelfName: '',
                },
                key: '',
                showPopup: true,
                showCheck: false,
                checkListValue: [],
                resultList: [],
                page: 1,
                rows: 10,
                refreshing: false,//刷新中...
                loading: false,//加载中...
                finished: false,//没有更多数据
                planId: this.$route.query.planId
            }
        },
        watch: {
            checkListValue: function (oldVal, newVal) {
                console.log(oldVal, newVal)
            }
        },
        computed: {
            checkAll: function () {
                if (this.resultList.length) {
                    return this.checkListValue.length === this.resultList.length;
                } else {
                    return false
                }
            }
        },
        mounted() {
            this._getData()
        },
        methods: {
            //简单查询 清空高级查询条件 赋值简单查询数据
            _search(value) {
                this.key = value
                this.formObj = this.$resetFields(this.formObj)
                this._refresh()
            },
            //高级搜索 清空key 查询
            _highSearch() {
                this.key = ''
                this.$refs.searchBar._hideHighSearch()
                this._refresh()
            },
            _clearHigh() {
                this.formObj = this.$resetFields(this.formObj)
            },
            _searchParams() {
                let data = {
                    page: this.page,
                    rows: this.rows,
                    planId: this.planId,
                    ...this.formObj
                };
                if (this.key) {
                    data.samplingNum = this.key
                }
                return this.$serializeForm(data)
            },
            _getData: async function () {
                let result = await samplingSummary.page(this._searchParams())
                this.resultList = [...(this.page === 1 ? [] : this.resultList), ...result.records]
                this.refreshing = false
                this.loading = false
                if (this.resultList.length === result.total) {
                    this.finished = true
                }
            },
            _refresh() {
                this.page = 1;
                this._getData()
            },
            _load() {
                this.page = this.page + 1;
                this._getData()
            },
            _back() {
                this.$router.go(-1)
            },
            _add() {
                this.$refs.shelvesSelect._open(this.planId)
            },
            _shelvesResult({testedType, shelfId}) {
                if (testedType === 1) {
                    this.$router.push({
                        path: '/sampling_list/sampling_list_add_net',
                        query: {testedType, shelfId, title: '抽样单添加-网络'}
                    })
                } else if (testedType === 0) {
                    this.$router.push({
                        path: '/sampling_list/sampling_list_add',
                        query: {testedType, shelfId, title: '抽样单添加-非网络'}
                    })
                } else {
                    this.$router.push({
                        path: '/sampling_list/sampling_list_add_agriculture',
                        query: {testedType, shelfId, title: '抽样单添加-农场品'}
                    })
                }
            },
            _longtapHandler() {
                this.showCheck = true
            },
            _hideCheck() {
                this.showCheck = false
                this.checkListValue = []
            },
            _checkAll() {
                if (this.checkAll) {
                    this.$refs.checkboxGroup.toggleAll();
                } else {
                    this.$refs.checkboxGroup.toggleAll(true);
                }
            },
            _tapItem(item) {
                if (this.showCheck) {
                    if (this.checkListValue.indexOf(item.id) === -1) {
                        this.checkListValue.push(item.id);
                    } else {
                        this.checkListValue.splice(this.checkListValue.indexOf(item.id), 1);
                    }
                } else {
                    if (item.testedType === 1) {
                        this.$router.push({path: '/sampling_list/sampling_list_detail_net', query: {id: item.id}})
                    } else if (item.testedType === 0) {
                        this.$router.push({path: '/sampling_list/sampling_list_detail', query: {id: item.id}})
                    } else {
                        this.$router.push({
                            path: '/sampling_list/sampling_list_detail_agriculture',
                            query: {id: item.id}
                        })
                    }
                }
            },
            _edit(item) {
                if (item.testedType === 1) {
                    this.$router.push({
                        path: '/sampling_list/sampling_list_add_net',
                        query: {id: item.id, title: '抽样单编辑-网络'}
                    })
                } else if (item.testedType === 0) {
                    this.$router.push({
                        path: '/sampling_list/sampling_list_add',
                        query: {id: item.id, title: '抽样单编辑-非网络'}
                    })
                } else {
                    this.$router.push({
                        path: '/sampling_list/sampling_list_add_agriculture',
                        query: {id: item.id, title: '抽样单编辑-农场品'}
                    })
                }
            },
            _print(item) {
                //调用第三放程序打开指定文件（必须是本地路径）
                this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                });
                var dtask = plus.downloader.createDownload(
                    this.$global.baseURL + '/drs/v1/sampling_summary/export_sampling?id=' + item.id, {}, (d, status) => {
                        if (status == 200) {
                            plus.runtime.openFile(d.filename);//cn.wps.moffice_eng-----wps的包名
                        }
                        this.$toast.clear();
                    });
                dtask.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                dtask.setRequestHeader('accessToken', localStorage.getItem('accessToken'));
                dtask.start();
            },
            _del(ids) {
                if (ids.length === 0) {
                    this.$toast('请至少选择一条数据！')
                } else {
                    this._delOk(ids)
                }
            },
            _delOk: async function (ids) {
                let result = await samplingSummary.deleteByIds(ids)
                if (result) {
                    this.$toast('操作成功！')
                    this._refresh()
                }
            },
            _goFile(id) {
                this.$router.push({path: '/sampling_list/file', query: {summaryId: id}})
            }
        }
    }
</script>

<style scoped>

</style>
