<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div class="filter">
        <label>{{$t('100089')}}：</label>
        <Select
          v-model="productname"
          label-in-value
          clearable
          filterable
          remote
          :remote-method="remoteMethod1"
          :loading="loading1"
          class="searchSelect"
        >
          <Option
            v-for="(item,index) in products"
            :value="item.code"
            :key="index"
          >{{ item.name }}({{item.code}})</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t('10300002')}}：</label>
        <Select v-model="type" label-in-value clearable class="searchSelect">
          <Option value="1">SN</Option>
          <Option value="2">BOX</Option>
        </Select>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="tosearch()">{{$t('1001')}}</Button>
        <Button type="success" class="twoWord" icon="md-add-circle" @click="add()">{{$t('1002')}}</Button>
        <Button
          type="warning"
          class="twoWord"
          icon="ios-create-outline"
          @click="edit()"
        >{{$t('1003')}}</Button>
        <Button
          type="error"
          class="twoWord intervalRight"
          icon="md-close-circle"
          @click="dele()"
        >{{$t('1004')}}</Button>
        <Button
          type="primary"
          class="fourWord"
          icon="md-download"
          @click="loadexcel()"
        >{{$t('1005')}}</Button>
        <Upload
          style="display:inline-block"
          ref="upload"
          :action="action"
          name="excel-file"
          :headers="headers"
          :show-upload-list="false"
          :on-format-error="handleFormatError"
          :on-success="handleSuccess"
          :on-error="handleError"
          :format="['xlsx']"
        >
          <Button type="primary" class="fourWord" icon="md-cloud-upload">{{$t('1006')}}</Button>
        </Upload>
        <Button
          type="primary"
          class="fourWord"
          icon="ios-cloud-download"
          @click="Export()"
        >{{$t('1007')}}</Button>
      </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        @on-selection-change="handleSelectRow"
        :columns="tableColumns1"
      ></Table>
      <div class="pageDiv">
        <div class="pageDirection">
          <Page
            :total="total"
            :current="page"
            :page-size="pagesize"
            @on-change="changePage"
            show-elevator
            show-sizer
            show-total
            @on-page-size-change="handlePageSize"
            :page-size-opts="[10,20,30,40,100]"
          ></Page>
        </div>
      </div>
      <Modal class="newModalClass" v-model="addmodal" :styles="{width:'400px'}">
        <p slot="header">
          <span v-if="modaltype===1">{{$t('1002')}}</span>
          <span v-if="modaltype===2">{{$t('1003')}}</span>
        </p>
        <div class="modal_body">
          <div class="filter">
            <label>
              <i>*</i>
              {{$t('100089')}}：
            </label>
            <Select
              v-model="addobj.productId"
              label-in-value
              class="searchSelect"
              filterable
              remote
              :remote-method="remoteMethod1"
              :loading="loading1"
            >
              <Option
                v-for="(item,index) in products"
                :value="item.code"
                :key="index"
              >{{ item.name }}({{item.code}})</Option>
            </Select>
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              {{$t('10300002')}}：
            </label>
            <Select v-model="addobj.ruleType" label-in-value class="searchSelect">
              <Option :value="1">SN</Option>
              <Option :value="2">BOX</Option>
            </Select>
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              {{$t('10300004')}}：
            </label>
            <InputNumber class="searchInput" type="text" v-model="addobj.step" :min="0" />
          </div>
          <div class="filter">
            <label>
              <i>*</i>
              {{$t('10300005')}}：
            </label>
            <Select
              v-model="addobj.codeType"
              label-in-value
              class="searchSelect"
              @on-change="codeTypeChange"
            >
              <Option :value="0">{{$t('5500241')}}</Option>
              <Option :value="1">{{$t('5500242')}}</Option>
              <Option :value="2">{{$t('5500243')}}</Option>
              <Option :value="4">{{$t('5500251')}}</Option>
            </Select>
          </div>
          <div class="filter" v-show="addobj.codeType===1">
            <label>
              <i>*</i>
              {{$t('10300006')}}：
            </label>
            <Select v-if="codeshow" v-model="addobj.codeFormat" label-in-value class="searchSelect">
              <Option v-for="item in codeFormats" :value="item.id" :key="item.id">{{ item.title }}</Option>
            </Select>
            <Input v-else v-model="addobj.codeFormat" class="searchInput" type="text" />
          </div>
          <div class="filter" v-show="addobj.codeType===2">
            <label>{{this.$t('10300009')}}：</label>
            <InputNumber class="searchInput" type="text" v-model="addobj.length" :min="0" />
          </div>
          <div class="filter" v-show="addobj.codeType===0||addobj.codeType===2">
            <label>{{this.$t('10300008')}}：</label>
            <Input class="searchInput" type="text" v-model="addobj.codeValue" />
          </div>
        </div>
        <div slot="footer">
          <Button type="text" size="large" @click="addmodal = false">{{$t('1033')}}</Button>
          <Button type="primary" v-if="modaltype===1" size="large" @click="adddata()">{{$t('1002')}}</Button>
          <Button
            type="primary"
            v-if="modaltype===2"
            size="large"
            @click="editdata()"
          >{{$t('1003')}}</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import axios from '@/libs/api.request';
export default {
    data () {
        return {
            action: axios.publicPath + 'acc/upload/UploadExcel?templateName=SnRule',
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            // 搜索
            loading1: false,
            products: [],
            productname: '',
            type: 0,
            modaltype: 1,

            // 添加
            codeFormats: [],
            codeshow: true,
            addobj: {
                productId: '', // 产品编号
                ruleType: '', // 规则类型
                step: 0, // 顺序
                codeType: '', // 编码类型
                codeFormat: '', // 编码格式
                length: 0, // 长度
                codeValue: '' // 编码值
            },

            tableData1: [],
            total: 0,
            page: 1,
            pagesize: 10,
            addmodal: false,
            detailobj: '',

            tableColumns1: [
                {
                    type: 'index2',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    render: (h, params) => {
                        return h(
                            'span',
                            params.index + (this.page - 1) * this.pagesize + 1
                        );
                    },
                    width: '70px'
                },

                {
                    title: this.$t('100089'),
                    key: 'productId'
                },
                {
                    title: this.$t('10300003'),
                    key: 'ruleDesc'
                },
                {
                    title: this.$t('10300004'),
                    key: 'step'
                },
                {
                    title: this.$t('10300005'),
                    key: 'codeDesc'
                },
                {
                    title: this.$t('10300006'),
                    key: 'codeFormat'
                },
                {
                    title: this.$t('10300007'),
                    key: 'lengthNull'
                },
                {
                    title: this.$t('10300008'),
                    key: 'value'
                }
            ]
        };
    },
    created () {
        this.iniproducts('');
        this.tosearch();
        this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
    },
    methods: {
        iniproducts (name) {
            var params = {
                name: name,
                count: 50
            };
            axios
                .request({
                    url: '/config/ProjectProduct/GetProductsByCode',
                    params,
                    method: 'get'
                })
                .then((res) => {
                    if (res.data.ret === 1 && res.data.data.length > 0) {
                        this.products = res.data.data;
                    }
                });
        },
        remoteMethod1 (name) {
            if (name !== '') {
                this.loading1 = true;
                setTimeout(() => {
                    this.loading1 = false;
                    this.iniproducts(name);
                }, 200);
            } else {
                this.iniproducts('');
            }
        },
        handleFormatError (file) {
            this.$Message.error(this.$t('950396') + file.name + this.$t('950397'));
        },
        handleSuccess (res, file) {
            if (res.ret == 1) {
                this.$Message.success(this.$t('950398'));
                this.tosearch();
            } else {
                if ((res.msg + '').indexOf(',') != -1) {
                    inittip(res.msg);
                } else {
                    this.$Message.error(this.$t(res.msg));
                }
            }
        },
        handleError () {
            this.$Message.error(this.$t('2010006') + '!');
        },
        handleSelectRow: function (data) {
            var ids = [];
            for (var i in data) {
                ids.push(data[i].id);
            }
            this.selectids = ids.join(',');
        },
        tosearch () {
            this.page = 1;
            this.pagesize = 10;
            this.search();
        },
        search () {
            var params = {
                productCode: this.productname,
                rule: this.type,
                // type,
                page: this.page,
                pagesize: this.pagesize
            };
            axios
                .request({
                    url: '/acc/SerinumConfig/GetList',
                    params,
                    method: 'get'
                })
                .then((res) => {
                    this.total = 0;
                    this.tableData1 = [];
                    if (
                        res.data.ret === 1 &&
            res.data.data != null &&
            res.data.data.length > 0
                    ) {
                        this.total = res.data.total;
                        this.mockTableData1(res.data.data);
                    }
                });
        },
        mockTableData1 (tablelist) {
            let data = [];
            tablelist.forEach((item) => {
                if (item) {
                    data.push({
                        productId: item.productId,
                        productCode: item.productCode,
                        ruleDesc: item.ruleDesc,
                        code: item.code,
                        codeDesc: item.codeDesc,
                        codeFormat: item.codeFormat,
                        step: item.step,
                        length: item.length,
                        value: item.value,
                        ruleKey: item.ruleKey,
                        id: item.id,
                        lengthNull:item.lengthNull
                    });
                }
            });
            this.tableData1 = data;
        },
        handleRowChange (currentRow, oldCurrentRow) {
            this.detailobj = currentRow;
        },
        handlePageSize (value) {
            this.pagesize = value;
            this.tableData1 = this.search();
        },
        changePage (value) {
            this.page = value;
            this.tableData1 = this.search();
        },
        codeTypeChange () {
            if (this.addobj.codeType === 1) {
                this.codeshow = true;
                this.codeFormats = [
                    {
                        id: 'YYDDD',
                        title: 'YYDDD'
                    },
                    {
                        id: 'YYYYMMDD',
                        title: 'YYYYMMDD'
                    },
                    {
                        id: 'YYMMDD',
                        title: 'YYMMDD'
                    }
                ];
            } else {
                this.codeshow = false;
            }
        },
        add () {
            this.modaltype = 1; // 添加
            this.addmodal = true;
            this.codeshow = true;
            this.addobj = {
                productId: '', // 产品编号
                ruleType: '', // 规则类型
                step: 0, // 顺序
                codeType: '', // 编码类型
                codeFormat: '', // 编码格式
                length: 0, // 长度
                codeValue: '' // 编码值
            };
        },
        adddata () {
            if(this.addobj.length===null)
            {
               this.addobj.length=0;
            }
            if (
                this.addobj.productId === '' ||
        this.addobj.ruleType === '' ||
        this.addobj.step === 0 ||
        this.addobj.step===null ||
        this.addobj.codeType === ''
            ) {
                this.$Message.error(this.$t('9000136'));
                return false;
            }
            if(this.addobj.codeType === 1){
                if(this.addobj.codeFormat === ''){
                    this.$Message.error(this.$t('9000136'));
                    return false;
                }
            }
            
            if(this.addobj.codeType === 0){
                this.addobj.length = 0
                this.addobj.codeFormat = ''
            }else if(this.addobj.codeType === 1){
                this.addobj.length = 0
                this.addobj.codeValue = ''
            }else if(this.addobj.codeType === 2){
                this.addobj.codeFormat = ''
            }else if(this.addobj.codeType === 4){
                this.addobj.codeFormat = ''
                this.addobj.length = 0
                this.addobj.codeValue = ''
            }
            let data = {
                productId: this.addobj.productId,
                ruleType: parseInt(this.addobj.ruleType),
                step: this.addobj.step,
                codeType: parseInt(this.addobj.codeType),
                codeFormat: this.addobj.codeFormat,
                length: this.addobj.length,
                codeValue: this.addobj.codeValue
            };
            axios
                .request({
                    url: '/acc/SerinumConfig/Add',
                    data,
                    method: 'post'
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('1055'));
                        this.addmodal = false;
                        this.detailobj = '';
                        this.tosearch();
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        dele () {
            if (
                this.detailobj === '' ||
        this.detailobj === undefined ||
        this.detailobj.id === undefined ||
        this.detailobj.id === 0
            ) {
                this.$Message.error(this.$t('1017'));
                return false;
            } else {
                var data = {
                    Id: this.detailobj.id,
                    resultStatus: this.detailobj.resultStatus
                };
                this.$Modal.confirm({
                    title: this.$t('1018'),
                    content: '',
                    width: '290px',
                    closable: true,
                    okText: this.$t('1004'),
                    onOk: () => {
                        axios
                            .request({
                                url: '/acc/SerinumConfig/Delete',
                                data,
                                method: 'post'
                            })
                            .then((res) => {
                                if (res.data.ret === 1) {
                                    this.$Message.success(this.$t('1058'));
                                    this.tosearch();
                                    this.detailobj = '';
                                } else {
                                    this.$Message.error(this.$t(res.data.msg));
                                }
                            });
                    }
                });
            }
        },
        edit () {
            this.modaltype = 2;
            if (
                this.detailobj === '' ||
        this.detailobj === undefined ||
        this.detailobj.id === undefined
            ) {
                this.$Message.error(this.$t('1017'));
                return false;
            }

            this.modaltype = 2; // 编辑
            this.addmodal = true;

            this.addobj.productId =
        this.detailobj.productId === null ? '' : this.detailobj.productId;
            this.addobj.ruleType = this.detailobj.ruleKey;
            this.addobj.step = this.detailobj.step;
            this.addobj.length =
        this.detailobj.length === '' ? 0 : parseInt(this.detailobj.length);
            this.addobj.codeValue = this.detailobj.value;
            this.addobj.codeType = this.detailobj.code;
            this.codeTypeChange();
            this.addobj.codeFormat = this.detailobj.codeFormat;
        },
        editdata () {
            if (
                this.addobj.productId === '' ||
        this.addobj.ruleType === '' ||
        this.addobj.step === 0 ||
        this.addobj.codeType === '' 
            ) {
                this.$Message.error(this.$t('9000136'));
                return false;
            }
            if(this.addobj.codeType === 1){
                if(this.addobj.codeFormat === ''){
                    this.$Message.error(this.$t('9000136'));
                    return false;
                }
            }

            if(this.addobj.codeType === 0){
                this.addobj.length = 0
                this.addobj.codeFormat = ''
            }else if(this.addobj.codeType === 1){
                this.addobj.length = 0
                this.addobj.codeValue = ''
            }else if(this.addobj.codeType === 2){
                this.addobj.codeFormat = ''
            }else if(this.addobj.codeType === 4){
                this.addobj.codeFormat = ''
                this.addobj.length = 0
                this.addobj.codeValue = ''
            }

            let data = {
                id: this.detailobj.id,
                productId: this.addobj.productId,
                ruleType: parseInt(this.addobj.ruleType),
                step: this.addobj.step,
                codeType: parseInt(this.addobj.codeType),
                codeFormat: this.addobj.codeFormat,
                length: this.addobj.length,
                codeValue: this.addobj.codeValue
            };
            axios
                .request({
                    url: '/acc/SerinumConfig/Update',
                    data,
                    method: 'post'
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.$Message.success(this.$t('1060'));
                        this.detailobj = '';
                        this.addmodal = false;
                        this.search();
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        loadexcel () {
            axios
                .request({
                    url: '/config/Download/GetTemplate?name=SnRule',
                    method: 'get'
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        window.location.href = axios.publicPath + '' + res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        Export () {
            let data = {
                productCode: this.productname,
                runtype: this.type
            };
            axios
                .request({
                    url: '/acc/SerinumConfig/ExportData',
                    data,
                    method: 'get'
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        window.location.href = axios.publicPath + '' + res.data.data;
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                });
        },
        unloadexcel () {
            let file = this.readyFiles[0];
            const data = new FormData();
            data.append('file', file);
            data.append('type', 2);
            axios
                .request({
                    url: '/acc/Upload/UploadExcel?templateName=SnRule',
                    data,
                    method: 'post'
                })
                .then((res) => {
                    if (res.data.ret === 1) {
                        this.tosearch();
                        this.$Message.success(this.$t('100378'));
                    } else {
                        this.$Message.error(this.$t(res.data.msg));
                    }
                })
                .catch((err) => {
                    this.$Message.error(this.$t(err.msg));
                });
        }
    }
};
</script>
<style lang="less" scoped>
</style>
