<template>
  <div>
    <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('100390')}}：</label>
        <Select v-model="materialId" label-in-value clearable class="searchSelect">
          <Option
            v-for="item in materiallist"
            :value="item.pn"
            :key="item.id"
          >{{item.pn}} {{ item.name }} {{item.spec}}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t('5500274')}}：</label>
        <Select v-model="typeid" label-in-value clearable class="searchSelect">
          <Option
            v-for="(item,index) in labeltypes"
            :value="item.dkey"
            :key="index"
          >{{item.dval}}</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="error"
          class="twoWord intervalRight"
          icon="md-close-circle"
          @click="del()"
        >{{$t('1004')}}</Button>
      </div>
    </div>
    <div class="divborder newTableDiv">
      <Table
        class="tableClass"
        @on-current-change="handleRowChange"
        @on-selection-change="handleSelectRow"
        highlight-row
        :data="tableData1"
        :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>
    </div>

    <!-- 添加弹窗 -->
    <Modal class="newModalClass" :title="$t('1002')" v-model="addmodal" :styles="{width:'600px'}">
        <div  class="modal_body" style="height:300px;">
          <div class="filter">
            <label><i>*</i>{{$t('100089')}}：</label>
            <Select
              v-model="addobj.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><i>*</i>{{$t('100390')}}：</label>
            <Select v-model="addobj.materialId" label-in-value clearable class="searchSelect">
              <Option
                v-for="item in materiallist"
                :value="item.pn"
                :key="item.id"
              >{{item.pn}} {{ item.name }} {{item.spec}}</Option>
            </Select>
          </div>
          <div class="filter">
            <label><i>*</i>{{$t('5500271')}}：</label>
            <Select v-model="addobj.printtype" label-in-value class="searchSelect">
              <Option :value="1">{{$t('5500272')}}</Option>
              <Option :value="2">{{$t('5500273')}}</Option>
            </Select>
          </div>
          <div class="filter">
            <label><i>*</i>{{$t('5500274')}}：</label>
            <Select v-model="addobj.typeid" label-in-value clearable class="searchSelect">
              <Option
              v-for="(item,index) in labeltypes"
              :value="item.dkey"
              :key="index"
            >{{item.dval}}</Option>
            </Select>
          </div>
          <div class="filter">
            <label><i>*</i>{{$t('5500292')}}：</label>
              <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="['txt','xls','xlsx']"
              >
                  <Button icon="md-folder" style="width:140px;">{{$t('600276')}}(txt,excel)</Button>
              </Upload>
              <span style="display:block;margin-left:105px;color:#2d8cf0;width:400px;">{{addobj.file_name}}</span>
          </div>
            <div style="display: flex;">
              <label><i>*</i>{{$t('600528')}}：</label>
              <div class="uploadMax">
                  <img :src="loadimg" alt />
                  <input
                    type="file"
                    name
                    ref="fileInteditimg"
                    id="face"
                    @change="unloadimg"
                    accept="image/png, image/gif, image/jpeg"
                  />
              </div>
          </div>
        </div>
        <div slot="footer">
          <Button type="text" size="large" @click="addmodal=false">{{$t('1033')}}</Button>
          <Button type="primary" size="large" @click="addpost">{{$t('1011')}}</Button>
        </div>
    </Modal>

  </div>
</template>

<script>
import axios from "@/libs/api.request";
export default {
  data() {
    return {
      loading1: false,
      addmodal:false,
      loadimg: require('../../../static/images/xiangjitwo.png'),
      action: this.axios.publicPath + 'acc/PrintLabelFile/UploadPrintLable',
      headers: {
          token: localStorage.getItem('token'),
          timestamp: localStorage.getItem('timestamp'),
          nonce: localStorage.getItem('nonce'),
          sign: localStorage.getItem('sign')
      },

      productname: "",
      products: [],
      materialId: "",
      materiallist: [],
      typeid: "",
      labeltypes: [], // 模板类型
      addobj:{
        productname:'',
        materialId:'',
        typeid:''
      },
      tableColumns1: [
        {
          type: "selection",
          width: 50,
          align: "center",
        },
        {
          type: "index2",
          title: this.$t(1008),
          key: "xuhao",
          width: 70,
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
        },
        {
          title: this.$t('100089'),
          key: "productid_value",
        },
        {
          title: this.$t('900933'),
          key: "pn",
        },
        {
          title: this.$t('5500271'),
          key: "printtype",
          render:(h,params)=>{
            var str = ""
            if(params.row.printtype === 1){
              str = this.$t('5500272')
            }else if(params.row.printtype === 2){
              str = this.$t('5500273')
            }
            return h('span',str);
          }
        },
        {
          title: this.$t('5500274'),
          key: "labeltype_value",
        },
        {
          title: this.$t('930136'),
          key: "labelfilename",
          render:(h,params)=>{
            return h('span',
              {
                style:{
                  color:'#2d8cf0',
                  cursor:'pointer'
                },
                attrs: {
                  // href: this.axios.publicPath + params.row.filepath,
                },
                on:{
                  click:()=>{
                    var url = params.row.filepath;
                    var filetype = ''
                    if(url!=""&&url!=undefined&&url!=null){
                      filetype = url.split('.')[1];
                      if(filetype==='txt'){
                        this.getTxtfile(params.row)
                      }else if(filetype==='xls'||filetype==='xlsx'){
                        window.location.href = this.axios.publicPath + '' + url
                      }
                    }
                  }
                }
              },params.row.labelfilename
            )
          }
        },
        {
          title: this.$t('1045'),
          key: "image",
          render:(h,params)=>{
            if(params.row.image===""||params.row.image===null||params.row.image===undefined){
              return 
            }
            return h('Poptip',
            {
              props:{
                trigger: 'hover',
                title: this.$t('1045'), // 图片
                placement: 'bottom',
                transfer: true,
                left: '30%'
              }
            },
            [
              h('Tag', this.$t('1045')),
              h(
                'div',
                {
                  slot: 'content',
                  style:{
                    width:'500px',
                    height:'500px',
                    overflow:'auto'
                  }
                },
                [
                  h('img', {
                    attrs: {
                      src: this.axios.publicPath + params.row.image,
                      style:
                        'border-radius: 2px;z-index:9999;width:100%;'
                    }
                  })
                ]
              )
            ])
          }
        },
        {
          title: this.$t('920139'),
          key: "uid_value",
        },
        {
          title: this.$t('920138'),
          key: "transdatetime",
        },
      ],
      tableData1: [],
      page: 1,
      pagesize: 10,
      total: 0,
      addobj:{
        productname:'',
        materialId:'',
        typeid:'',
        printtype:1,
        file_name:'',
        file_url:'',
        image:''
      },
      selectids:[]
    };
  },
  created() {
    this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1)
    this.iniproducts("");
    this.loadMaterial();
    this.getlabeltypes()
    this.tosearch();
  },
  methods: {
    getTxtfile(file){
      axios
          .request({
            url: "/config/Download/DownloadFile?file_url=" + file.filepath,
            method: "get",
          })
          .then((res) => {
            if (res.data.ret === 1) {
              var info = res.data.data;
              var content = info.content;
              // 创建隐藏的可下载链接
              var eleLink = document.createElement("a");
              eleLink.download = file.labelfilename;
              eleLink.style.display = "none";
              // 字符内容转变成blob地址
              var blob = new Blob([content]);
              eleLink.href = URL.createObjectURL(blob);
              // 触发点击
              document.body.appendChild(eleLink);
              eleLink.click();
              // 然后移除
              document.body.removeChild(eleLink);

            } else {
              this.$Message.error(this.$t(res.data.msg));
            }
          });
    },
    unloadimg () {
        // 上传照片
        const file = this.$refs.fileInteditimg.files[0];
        const data = new FormData();
        data.append('file', file);
        axios
            .request({
                url: '/config/upload/UploadImage',
                data,
                method: 'post'
            })
            .then(res => {
                if (res.data.ret === 1) {
                    this.$Message.success(this.$t('100378'));
                    this.loadimg = axios.publicPath + res.data.data;
                    this.addobj.image = res.data.data;
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
            .catch(err => {
                alert(this.$t(err.msg));
            });
    },
    getlabeltypes(){
      axios
        .request({
          url: "/config/Dict/GetDictByCat?cat=labeltype",
          method: "get",
        })
        .then((res) => {
          this.labeltypes = []
          if (res.data.ret === 1 && res.data.data.length > 0) {
            this.labeltypes = res.data.data;
          }
        });
    },
    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("");
      }
    },
    // 加载全部物料
    loadMaterial() {
      axios
        .request({
          url: "config/Material/GetMaterialList",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            this.materiallist = res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    tosearch() {
      this.page = 1;
      this.pagesize = 10;
      this.search();
    },
    search() {
      var params = {
        productid: this.productname,
        pn: this.materialId,
        labeltype: this.typeid,
        page: this.page,
        pagesize: this.pagesize,
      };
      this.selectids = []
      axios
        .request({
          url: "/acc/PrintLabelFile/getList",
          params,
          method: "get",
        })
        .then((res) => {
          this.tableData1 = [];
          this.total = 0;
          if (res.data.ret === 1) {
            this.total = res.data.total;
            this.tableData1 = res.data.data;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    add() {
      this.addmodal = true
      this.loadimg= require('../../../static/images/xiangjitwo.png')
      this.addobj = {
        productname:'',
        materialId:'',
        typeid:'',
        printtype:1,
        file_name:'',
        file_url:''
      }
    },
    addpost(){
      if(this.addobj.productname===""||this.addobj.productname===undefined){
        this.$Message.error(this.$t('9000140'));
        return false;
      }
      if(this.addobj.materialId===""||this.addobj.materialId===undefined){
        this.$Message.error(this.$t('9100056'));
        return false;
      }
      if(this.addobj.typeid===""||this.addobj.typeid===undefined){
        this.$Message.error(this.$t('5500293'));
        return false;
      }
      if(this.addobj.file_url===""||this.addobj.file_url===undefined){
        this.$Message.error(this.$t('5500294'));
        return false;
      }
      if(this.addobj.image===""||this.addobj.image===undefined){
        this.$Message.error(this.$t('5500295'));
        return false;
      }
      var data = {
        productid:this.addobj.productname,
        pn:this.addobj.materialId,
        labeltype:this.addobj.typeid,
        printtype:this.addobj.printtype,
        labelfilename:this.addobj.file_name,
        filepath:this.addobj.file_url,
        image:this.addobj.image
      }
      axios
        .request({
          url: "/acc/PrintLabelFile/add",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            this.$Message.success(this.$t('1055'));
            this.addmodal = false
            this.tosearch()
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
      
    },
    del() {
      if(this.selectids.length === 0){
        this.$Message.error(this.$t('1017'));
        return false;
      }
      this.$Modal.confirm({
        title: this.$t('1018'),
        content: '',
        width: '290px',
        closable: true,
        okText: this.$t('1004'),
        onOk: () => {
        axios
            .request({
                url: '/acc/PrintLabelFile/Delete?id='+this.selectids.join(),
                method: 'get'
            })
            .then(res => {
                if (res.data.ret === 1) {
                    this.$Message.success(this.$t('1058'))
                    this.search()
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        }
    })
    },
    handleRowChange(currentRow, oldCurrentRow) {
      this.detailobj = currentRow;
    },
    handleSelectRow: function (data) {
      this.selectids = [];
      for (var i in data) {
        if (this.selectids.indexOf(data[i].id) < 0) {
          this.selectids.push(data[i].id);
        }
      }
    },
    changePage(value) {
      this.page = value;
      this.search(this.page, this.pagesize);
    },
    handlePageSize(value) {
      this.pagesize = value;
      this.search(this.page, this.pagesize);
    },
    handleFormatError (file) {
        this.$Message.error(this.$t('1163'));
    },
    handleSuccess (res, file) {
      if (res.ret == 1) {
        this.$Message.success(this.$t('100378'));
        this.addobj.file_name = file.name;
        this.addobj.file_url = res.data;
      } else {
        this.$Message.error(this.$t(res.msg));
      }
    },
    handleError () {
        this.$Message.error(this.$t('1074'));
    },
  },
};
</script>

<style lang="less" scoped>
</style>
