<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form>
        <el-form-item>
          <el-input
            v-model="listQuery.tempName"
            placeholder="模板名称"
            style="width: 200px"
            @keyup.enter.native="handleFilter"
          />
          <el-select
            v-model="listQuery.jianyanleibie"
            placeholder="请选择检验类别"
            style="width: 150px"
            clearable
            @change="getNblbListBySearchJylb"
          >
            <el-option
              v-for="item in jylbList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          <el-select
            v-model="listQuery.shebeizhongleidaima"
            placeholder="请选择设备种类"
            style="width: 150px"
            clearable
            @change="getNblbListBySbzl"
          >
            <el-option
              v-for="item in sbzlList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="listQuery.neibuleibie"
            placeholder="请选择内部类别"
            style="width: 150px"
            clearable
          >
            <el-option
              v-for="item in nblbList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
          <el-select
            v-model="listQuery.bglx"
            placeholder="请选择类型"
            style="width: 120px"
            clearable
          >
            <el-option
              v-for="item in bglxList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="listQuery.tempCategory"
            placeholder="模板类型"
            style="width: 200px"
            clearable
          >
            <el-option
              v-for="item in categoryList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button type="primary" icon="el-icon-edit" @click="showCreate">
            添加
          </el-button>
          <el-button
            type="warning"
            icon="el-icon-magic-stick"
            @click="showConvert"
          >
            转换标签
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="deleteTemplate"
          >
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="list"
      :data="list"
      border
      fit
      highlight-current-row
      @row-click="onRowClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column
        :formatter="formatter.formatterCategory"
        align="center"
        label="检验类别"
        prop="jianyanleibie"
        width="100"
      />
      <el-table-column
        :formatter="fmSbzl"
        align="center"
        label="设备种类"
        prop="shebeizhongleidaima"
        width="100"
      />
      <el-table-column align="left" label="名称" prop="tempName" />
      <el-table-column
        align="center"
        label="版本号"
        prop="version"
        width="100"
      />
      <el-table-column
        :formatter="fmBglx"
        align="center"
        label="报告类型"
        prop="bglx"
        width="80"
      />
      <el-table-column align="center" label="是否在用" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active="false"
            inactive="true"
            @change="editStatus(scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="管理" width="190">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            circle
            title="编辑"
            @click="showUpdate(scope.row,scope.$index)"
          />
          <el-button
            type="success"
            size="mini"
            icon="el-icon-download"
            circle
            title="下载"
            @click="download(scope.$index)"
          />
          <el-upload
            size="mini"
            :show-file-list="false"
            :before-upload="beforeUpload"
            style="display: inline"
            action="123"
          >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-upload"
              circle
              title="上传"
              @click="upload(scope.$index)"
            />
          </el-upload>
          <el-button
            type="primary"
            size="mini"
            circle
            title="复制"
            @click="copyTemplate(scope.row,scope.$index)"
          >
            <svg-icon icon-class="clipboard" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page-num.sync="listQuery.pageNum"
      :page-row.sync="listQuery.pageRow"
      @pagination="getList"
    />
    <el-dialog title="模板标签转换" :visible.sync="dialogConvertVisible">
      <el-form
        ref="formConvert"
        :model="formConvert"
        class="small-space"
        label-position="left"
        label-width="120px"
        style="width: 500px; margin-left: 50px"
      >
        <el-form-item label="转换表格位置" prop="replaceTableIndex" required>
          <el-input-number
            v-model="formConvert.replaceTableIndex"
            :min="0"
            :max="100"
          />
        </el-form-item>
        <el-upload
          ref="upload"
          class="upload-demo"
          drag
          action=""
          accept="application/msword"
          :auto-upload="false"
          :limit="1"
          :http-request="handleUpload"
          :file-list="fileList"
          multiple
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogConvertVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="convertLabel">
          转 换
        </el-button>
      </div>
    </el-dialog>
    <drawerDialog :id="id" :drawer.sync="drawer" :type="temType" :index="templateIndex" :template-list="list" :parent-list="parentList" @closeTemplateDrawer="closeTemplateDrawer" />
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import drawerDialog from '@/components/drawerDialog'
export default {
  name: 'FlowTemplate',
  components: { Pagination, drawerDialog },
  data() {
    return {
      total: 0, // 分页组件--数据总条数
      list: [], // 表格的数据
      listQuery: {
        pageNum: 1, // 页码
        pageRow: 20, // 每页条数
        neibuleibie: null
      },
      drawer: false,
      dialogVisible: false,
      textMap: {
        create: '创建模板',
        update: '编辑模板'
      },
      gridData: [],
      options: [],
      sbzlList: [],
      sblbList: [],
      sbpzList: [],
      parentList: [],
      jylbList: [],
      nblbList: [],
      bglxList: [],
      dicCodeList: [],
      temType: null,
      categoryList: [
        {
          value: 'YSJL',
          label: '原始记录'
        }, {
          value: 'JYBG',
          label: '检验报告'
        }, {
          value: 'OTHER',
          label: '其他'
        }, {
          value: 'HZD',
          label: '回执单'
        }, {
          value: 'RWD',
          label: '任务单'
        }
      ],
      formTemplate: {},
      dialogFormVisible: false,
      dialogStatus: 'create',
      multipleSelection: [],
      shebeipinzhongdaima: [],
      id: 0,
      checkedId: '',
      neibuleibie: [],
      dialogConvertVisible: false,
      formConvert: {},
      fileList: [],
      uploadFile: {},
      sbpzLevelStatus: false,
      templateIndex: 0
    }
  },
  created() {
    this.getList()
    this.getSbList(undefined, undefined, 1)
    this.getParentList()
    this.getBglxList()
    this.getJylbList()
    this.getTemplateIdentification()
  },
  methods: {
    closeTemplateDrawer() {
      this.drawer = false
    },
    //  获取模板标识集合
    getTemplateIdentification() {
      this.api({
        url: '/dicData/getDicDataByTypeCode',
        method: 'get',
        params: {
          typeCode: 'TEMPLATE_IDENTIFICATION'
        }
      }).then((data) => {
        this.options = data
      })
    },
    getList() {
      // 查询列表
      this.api({
        url: '/template/list',
        method: 'get',
        params: this.listQuery
      }).then((data) => {
        this.list = data.list
        console.log(data, '返回参数')
        this.total = data.total
      })
    },
    getSblbList(val) {
      this.formTemplate.shebeileibiedaima = ''
      this.sbpzList = []
      this.shebeipinzhongdaima = []
      this.getSbList(val, undefined, 2)
      // 新增与内部类别级联关系
      const jylb = this.formTemplate.jianyanleibie
      this.neibuleibie = []
      this.getCategoryList('nblb', jylb, val)

      this.shebeipinzhongdaima = []
      this.sbpzLevelStatus = false
      this.getSbList(
        this.formTemplate.shebeizhongleidaima,
        this.sbpzLevelStatus ? this.formTemplate.shebeileibiedaima : undefined,
        this.sbpzLevelStatus ? 3 : 4
      )
    },
    getSbpzList() {
      this.shebeipinzhongdaima = []
      this.getSbList(
        this.formTemplate.shebeizhongleidaima,
        this.sbpzLevelStatus ? this.formTemplate.shebeileibiedaima : undefined,
        this.sbpzLevelStatus ? 3 : 4
      )
    },
    getSbList(sbzl, sblb, level) {
      this.api({
        url: '/sedirectory/getList',
        method: 'get',
        params: {
          sbzl: sbzl,
          sblb: sblb,
          level: level
        }
      }).then((data) => {
        switch (level) {
          case 1:
            this.sbzlList = data
            break
          case 2:
            this.sblbList = data
            break
          case 3:
            this.sbpzList = data
            break
          default:
            this.sbpzList = data
            break
        }
      })
    },
    getParentList() {
      this.api({
        url: '/template/getTemplateListByBglx',
        method: 'get',
        params: {
          bglx: 1
        }
      }).then((data) => {
        this.parentList = data
      })
    },
    getBglxList() {
      this.api({
        url: '/dicData/getDicDataByTypeCode',
        method: 'get',
        params: {
          typeCode: 'REPORT_CLASS'
        }
      }).then((data) => {
        this.bglxList = data
      })
    },
    getJylbList() {
      this.getCategoryList('jylb', null, null)
    },
    getNblbListBySbzl(val) {
      const jylb = this.listQuery.jianyanleibie
      if (
        val !== undefined &&
        val !== '' &&
        (jylb === undefined || jylb === '')
      ) {
        this.$message.warning('选择内部类别，请先选择检验类别')
        return false
      }
      this.listQuery.neibuleibie = null
      this.getCategoryList('nblb', jylb, val)
    },
    getNblbListBySearchJylb(val) {
      const sbzl = this.listQuery.shebeizhongleidaima
      if (
        val !== undefined &&
        val !== '' &&
        (sbzl === undefined || sbzl === '')
      ) {
        this.$message.warning('请选择设备种类')
        return false
      }
      this.listQuery.neibuleibie = null
      this.getCategoryList('nblb', val, sbzl)
    },
    getNblbListByJylb(val) {
      const sbzl = this.formTemplate.shebeizhongleidaima
      this.neibuleibie = []
      this.getCategoryList('nblb', val, sbzl)
    },
    getCategoryList(type, parentCode, species) {
      this.api({
        url: '/category/getCategoryList',
        method: 'get',
        params: {
          parentCode: parentCode,
          species: species
        }
      }).then((data) => {
        switch (type) {
          case 'jylb':
            this.jylbList = data
            return ''
          case 'nblb':
            this.nblbList = data
            return ''
        }
      })
    },
    getDicCodeList(val) {
      for (let i = 0; i < this.bglxList.length; i++) {
        if (val === 1) {
          this.dicCodeList = []
          break
        } else if (val === this.bglxList[i].value) {
          this.getDicDataByTypeCode(
            this.bglxList[i].code,
            'dicCode',
            this.bglxList[i].id
          )
          break
        }
      }
    },
    getDicDataByTypeCode(val, type, parentId) {
      this.api({
        url: '/dicData/getDicDataByTypeCode',
        method: 'get',
        params: {
          typeCode: val,
          parentId: parentId
        }
      }).then((data) => {
        if (type === 'dicCode') {
          this.dicCodeList = data
        }
      })
    },
    showCreate() {
      this.formTemplate = {
        showPageStatus: false,
        hasCheckedPage: false
      }
      this.temType = 2
      this.templateIndex = null
      this.id = null
      this.dialogStatus = 'create'
      this.drawer = true
    },
    copyTemplate(row, $index) {
      this.id = row.id
      this.temType = 1
      this.templateIndex = $index
      this.dialogStatus = 'create'
      this.drawer = true
    },
    showUpdate(row, $index) {
      console.log(row, $index, '行')
      this.dialogStatus = 'update'
      this.id = row.id
      this.temType = 0
      this.templateIndex = $index
      this.drawer = true
      console.log(this.drawer, $index, '打开')
    },
    handleChange(value) {
      this.formLabelAlign.indexFromRight = value
    },
    onsubmit() {
      console.log(this.formLabelAlign)
      this.api({
        url: '/templateJyxm',
        method: 'post',
        data: this.formLabelAlign
      }).then((res) => {
        this.dialogVisible = false
        this.getList()
        this.getDemoList()
      })
    },
    loadFormData($index) {
      this.$set(this, 'formTemplate', this.list[$index])
      this.getSbList(this.formTemplate.shebeizhongleidaima, undefined, 2)
      this.sbpzLevelStatus = false
      this.getSbList(
        this.formTemplate.shebeizhongleidaima,
        this.sbpzLevelStatus ? this.formTemplate.shebeileibiedaima : undefined,
        this.sbpzLevelStatus ? 3 : 4
      )
      this.shebeipinzhongdaima = JSON.parse(
        this.formTemplate.shebeipinzhongdaima
      )
      this.neibuleibie = JSON.parse(this.formTemplate.neibuleibie)
      this.getDicCodeList(this.formTemplate.bglx)
      this.getCategoryList(
        'nblb',
        this.formTemplate.jianyanleibie,
        this.formTemplate.shebeizhongleidaima
      )
    },
    beforeUpload(file) {
      const isDoc = file.type === 'application/msword'
      if (!isDoc) {
        this.$message.error('只能上传doc格式的文件')
        return false
      }
      const fd = new FormData()
      fd.append('file', file)
      fd.append('id', this.checkedId)
      this.preview({
        url: '/upload/uploadTemplate',
        method: 'post',
        data: fd
      }).then(() => {
        this.$message.success('上传成功！')
      })
    },
    upload($index) {
      this.checkedId = this.list[$index].id
    },
    download($index) {
      this.preview({
        url: '/download/downloadTemplate',
        method: 'get',
        params: {
          id: this.list[$index].id
        }
      }).then((data) => {
        window.open(process.env.VUE_APP_PREVIEW_API + data)
      })
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.getList()
    },
    getIndex($index) {
      // 表格序号
      return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
    },
    onRowClick(row) {
      this.$refs.list.toggleRowSelection(row)
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    createTemplate() {
      // 添加新模板
      this.$refs['formTemplate'].validate((valid) => {
        if (valid) {
          this.formTemplate.shebeipinzhongdaima = JSON.stringify(
            this.shebeipinzhongdaima
          )
          this.formTemplate.neibuleibie = JSON.stringify(this.neibuleibie)
          this.api({
            url: '/template/add',
            method: 'post',
            data: this.formTemplate
          }).then(() => {
            this.$message.success('添加成功。')
            this.getList()
            this.dialogFormVisible = false
          })
        } else {
          return false
        }
      })
    },
    updateTemplate() {
      // 修改用户信息
      this.$refs['formTemplate'].validate((valid) => {
        if (valid) {
          this.formTemplate.shebeipinzhongdaima = JSON.stringify(
            this.shebeipinzhongdaima
          )
          this.formTemplate.neibuleibie = JSON.stringify(this.neibuleibie)
          this.api({
            url: '/template/update',
            method: 'post',
            data: this.formTemplate
          }).then(() => {
            this.dialogFormVisible = false
            this.$message.success('更新成功。')
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    deleteTemplate() {
      this.$confirm('确定删除当前选中记录?', '提示', {
        confirmButtonText: '确定',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        this.api({
          url: '/template',
          method: 'delete',
          params: {
            ids: this.$refs.list.selection.map(row => row.id)
          },
          paramsSerializer: function(params) {
            return require('qs').stringify(params, { indices: false })
          }
        }).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.getList()
            }
          })
        })
      })
    },
    editStatus($index) {
      const template = this.list[$index]
      this.api({
        url: '/template',
        method: 'put',
        data: template
      }).then(() => {
        this.getList()
      })
    },
    closeDialog() {
      this.shebeipinzhongdaima = []
      this.sbpzList = []
      this.sblbList = []
      this.neibuleibie = []
      this.$refs.formTemplate.resetFields()
    },
    fmBglx(row, column, cellValue) {
      for (let i = 0; i < this.bglxList.length; i++) {
        if (this.bglxList[i].value === cellValue) {
          return this.bglxList[i].name
        }
      }
    },
    fmSbzl(row, column, cellValue) {
      for (let i = 0; i < this.sbzlList.length; i++) {
        if (this.sbzlList[i].value === cellValue) {
          return this.sbzlList[i].label
        }
      }
    },
    showConvert() {
      this.dialogConvertVisible = true
    },
    convertLabel() {
      this.$refs['formConvert'].validate((valid) => {
        if (valid) {
          this.$refs.upload.submit()
        } else {
          return false
        }
      })
    },
    handleUpload(back) {
      const fd = new FormData()
      fd.append('file', back.file)
      fd.append('replaceTableIndex', this.formConvert.replaceTableIndex)
      this.preview({
        url: '/upload/replaceLabel',
        method: 'post',
        data: fd
      }).then((data) => {
        window.open(data)
      })
    }
  }
}
</script>
<style scoped>
.el-alert__content {
  width: 150px;
}
.left {
  width: 53%;
  height: 90%;
  float: left;
  padding: 10px;
  box-shadow: 2px 2px 5px #c8c8c8;
}
.right {
  width: 45%;
  height: 90%;
  float: right;
  padding: 10px;
  box-shadow: 2px 2px 5px #c8c8c8;
}
.funbox {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.bottomPage {
  width: 100%;
  text-align: center;
}
</style>
