<template>
  <!-- 钢瓶档案 -->
  <div>
    <actionBar menuTitle="钢瓶档案" :operateList="operateList" :formList="formList" :ruleForm="searchRuleForm"
      @openModel="openModel" @searchProtocol="searchProtocol">
    </actionBar>
    <tables :key="Math.random()" :suspension="true" :tableList="tableList" :tableData="tableData"
      @buttonData="buttonData"></tables>
    <!-- 分页 -->
    <div class="paging_bottom" v-if="Total">
      <pagination :total="Total" :currentPage="Pagination.PageIndex" @changeSize="changeSize"
        @changeCurrent="changeCurrent">
      </pagination>
    </div>
    <el-dialog :title="staffTitle" :visible.sync="cylinderDialog" width="800px" :close-on-click-modal="false"
      @close="closeDialog">
      <forms ref="childRules" :formNewList="cylinderRule" :ruleForm="cylinderForm" labelWidth="160px"></forms>
      <span slot="footer" class="dialog-footer" v-if="operationType != 'logs'">
        <el-button plain @click="cylinderDialog = false">取 消</el-button>
        <el-button type="primary" :loading="confirmLoading" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="批量导入" :visible.sync="bulkImportVisible" width="600px" @close="importClose">
      <div class="card_bulkImport">
        <el-upload ref="mYupload" class="upload-demo" drag action="#" :limit="1" multiple :http-request="UploadImage">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">请上传xls或者xlsx格式文件</div>
        </el-upload>
        <div style="margin-top: 15px;">
          <el-button size="medium" type="primary" icon="el-icon-upload" :loading="importFlag"
            @click="immediateImport">确定导入</el-button>
          <el-button size="medium" icon="el-icon-download" :loading="downloadFlag"
            @click="templateDownload">模板下载</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getGasCylinder,
    getGasCylinderDetails,
    addGasCylinder,
    putGasCylinder,
    delGasCylinder,
    waybillImport,
    exportTemplate,
  } from '@/api/inspection'
  import actionBar from '@/components/actionBar'
  import tables from '@/components/tables'
  import pagination from '@/components/pagination'
  import forms from '@/components/forms'
  import {
    employee,
    cylinderformRules
  } from "./cylinder.js";
  export default {
    components: {
      actionBar,
      tables,
      pagination,
      forms
    },
    data() {
      return {
        formList: [{
          type: 'input',
          label: '单位内编号',
          field: 'innerCode',
          placeholder: '单位内编号',
        }, ],
        searchRuleForm: {
          innerCode: '',
        },
        operateList: [{
          type: 'import',
          title: '导入',
          icon: 'el-icon-upload',
        }, {
          type: 'add',
          title: '添加钢瓶',
          icon: 'el-icon-plus',
        }],
        tableList: employee(),
        tableData: [],
        Pagination: {
          PageIndex: 1,
          PageSize: 10,
        },
        Total: 0,
        staffTitle: '添加钢瓶',
        searchValue: {},
        cylinderDialog: false,
        cylinderRule: cylinderformRules(),
        cylinderForm: {},
        confirmLoading: false,
        operationType: '',
        clientId: '',
        bulkImportVisible: false,
        importFlag: false,
        downloadFlag: false,
        importFile: null,
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      // 搜索
      searchProtocol(value) {
        this.searchValue = value
        this.getList()
      },
      // 获取钢瓶档案列表
      getList() {
        var params = {
          page: this.Pagination.PageIndex,
          pageSize: this.Pagination.PageSize,
          ...this.searchValue
        }
        getGasCylinder(params).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.Total = res.data.count
          }
        })
      },
      // 获取钢瓶档案详情
      getDetails(innerCode) {
        this.loading = true
        getGasCylinderDetails(innerCode).then(res => {
          if (res.code == 200) {
            this.ruleForm = res.data
          }
          this.loading = false
        })
      },
      openModel(type) {
        this.operationType = type
        if (type == 'add') {
          this.staffTitle = '添加钢瓶'
          const arr = [...this.cylinderRule]
          arr.forEach((item, index) => {
            item.disabled = false
          })
          this.cylinderRule = arr
          this.cylinderDialog = true
        } else if (type == 'import') {
          this.bulkImportVisible = true
        }
      },
      buttonData(row, type) {
        let arrRow = JSON.parse(JSON.stringify(row))
        if (type == 'logs') {
          this.cylinderForm = arrRow
          this.staffTitle = '钢瓶详情'
          const arr = [...this.cylinderRule]
          arr.forEach((item, index) => {
            item.disabled = true
          })
          this.cylinderRule = arr
          this.cylinderDialog = true
          // this.getDetails(row.inner_code)
        } else if (type == 'edit') {
          this.cylinderForm = arrRow
          this.staffTitle = '编辑钢瓶'
          this.clientId = arrRow.id
          this.cylinderDialog = true
        } else if (type == 'del') {
          this.getCancelOrder(arrRow.id)
        }
        this.operationType = type
      },
      // 弹窗表单添加
      handleAdd() {
        let flag = this.$refs['childRules'].validateForm();
        if (flag) {
          var params = {
            ...this.cylinderForm,
          }
          if (this.operationType == 'edit') {
            params.id = this.clientId
            putGasCylinder(params).then(res => {
              if (res.code == 200) {
                this.getList()
                this.cylinderDialog = false
              }
            })
          } else {
            addGasCylinder(params).then(res => {
              if (res.code == 200) {
                this.getList()
                this.cylinderDialog = false
              }
            })
          }
        } else {
          this.$message.error('表单信息不完整，请继续填写完整');
        }
      },
      // 删除钢瓶
      getCancelOrder(ID) {
        this.$confirm('此操作将永久删除该钢瓶, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delGasCylinder({
            id: ID,
          }).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.getList()
            }
          })
        }).catch(() => {
          // console.log('取消')
        });
      },
      // 导入
      immediateImport() {
        if (this.importFile) {
          this.importFlag = true
          let formData = new FormData();
          formData.append('file', this.importFile);
          formData.append('customerName', this.orderCustomer);
          waybillImport(formData).then(res => {
            if (res.code == 200) {
              this.bulkImportVisible = false
              this.importFlag = false
              this.getList()
              this.$message({
                message: '恭喜你，导入成功',
                type: 'success'
              });
            }
          })
        } else {
          this.$message({
            message: '请先选择上传文件',
            type: 'warning'
          });
        }
      },
      // 导出模板
      templateDownload() {
        this.downloadFlag = true
        exportTemplate().then(response => {
          let arrList = response.fileName.split('.')
          let fixedStr = decodeURIComponent(arrList[0]);
          let filename = fixedStr + '.' + arrList[1]
          // this.blobDownload(response, filename)
          this.blobDownload(response.data, filename)
          this.downloadFlag = false
        })
      },
      // 导出文件流
      blobDownload(data, name) {
        let m = this;
        var content = data;
        var data = new Blob([content], {
          type: "application/vnd.ms-excel;charset=utf-8"
        });
        var downloadUrl = window.URL.createObjectURL(data);
        var anchor = document.createElement("a");
        anchor.href = downloadUrl;
        anchor.download = name;
        anchor.click();
        window.URL.revokeObjectURL(data);
      },
      // 上传文件
      UploadImage(param) {
        this.importFile = param.file
      },
      changeSize(val) {
        this.Pagination.PageSize = val
        this.getList()
      },
      changeCurrent(val) {
        this.Pagination.PageIndex = val
        this.getList()
      },
      importClose() {
        this.importFile = null
        this.$refs['mYupload'].clearFiles();
      },
      closeDialog() {
        const arr = [...this.cylinderRule]
        arr.forEach((item, index) => {
          item.disabled = false
        })
        this.cylinderRule = arr
        this.cylinderForm = {}
        this.$refs['childRules'].resetCheck();
      }
    }
  }
</script>

<style lang="scss" scoped>
  .card_bulkImport {
    width: 100%;
  }

  ::v-deep .el-upload {
    width: 100%;
  }

  ::v-deep .el-upload-dragger .el-upload__text {
    color: #fff;
  }

  ::v-deep .el-upload__tip {
    color: #fff;
  }

  ::v-deep .el-upload-list__item-name {
    color: #fff;
  }

  ::v-deep .el-upload-list__item-name:hover {
    color: #000;
  }

  ::v-deep .el-upload-dragger {
    width: 100%;
    background-color: unset !important;
  }
</style>
