<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :exportList="exportList"
    :optionsEvensGroup="optionsEvensGroup"
    :operation="operation()"
    :tableEvents="tableEvents"
    :tableAttributes="tableAttributes"
    :columnParsing="columnParsing"
  >
    <!-- 弹窗 -->
    <el-dialog
      title="产品信息"
      :visible.sync="showDialogForm"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <el-form ref="diaLogForm" :model="diaLogForm" label-width="70px" :rules="rules" label-position="left">
        <el-form-item label="类型" prop="type">
          <el-select v-model="diaLogForm.type" filterable placeholder="请选择">
            <el-option v-for="item in distList" :key="item.dictCode" :label="item.dictValue" :value="item.dictCode">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="diaLogForm.name" size="normal"></el-input>
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="diaLogForm.model" size="normal"></el-input>
        </el-form-item>
        <el-form-item label="编码" prop="number">
          <el-input v-model="diaLogForm.number" size="normal"></el-input>
        </el-form-item>
        <el-form-item label="体积" prop="volume">
          <el-input
            v-model.number="diaLogForm.volume"
            type="number"
            @mousewheel.native.prevent
            size="normal"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click=";(showDialogForm = false), resetForm(), resetInfo()">取 消</el-button>
        <el-button type="primary" @click="hanleInfo">确 定</el-button>
      </div>
    </el-dialog>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import add_callback_mixin from '@/components/template/add_callback_mixin.js'
import Popu from '@/components/template/popu.vue'
import { downloadFiles, handleImport } from '@/utils/util'
import {
  getDistList,
  getMachineAdd,
  getMachineDel,
  getMachineEdit,
  getMachineLlistV2,
  exportMachineLlistV2
} from '@/api/basic_data/material'
export default {
  components: { TemplatePage, Popu },
  mixins: [import_mixin, add_callback_mixin],
  data() {
    return {
      visible: false,
      // 事件组合
      // 事件组合
      optionsEvensGroup: [
        [
          [
            {
              name: '新增',
              click: this.addOn(() => {
                this.showDialogForm = true
                this.type = 1
              }),
              isRole: this.$checkBtnRole('add', this.$route.meta.roles)
            }
          ]
        ],
        [
          [
            {
              name: '批量删除',
              click: async () => {
                if (this.recordSelected.length === 0) {
                  this.$message.error('请选择需要删除的数据')
                  return
                }
                let ids = this.recordSelected.map(v => {
                  return v.id
                })
                let params = ids
                await getMachineDel(params)
                this.$refs.pageRef.refreshList()
                this.$message.success('批量删除成功')
              },
              isRole: this.$checkBtnRole('del', this.$route.meta.roles)
            }
          ]
        ]
        // [
        //   [
        //     {
        //       name: '导入模版',
        //       click: () => {
        //         materialCategoryTemplateExcel({}, `${this.$route.meta.title}`)
        //           .then(res => {
        //             this.$message({
        //               message: '下载成功',
        //               type: 'success'
        //             })
        //           })
        //           .catch(err => {
        //             this.$message.error('下载失败')
        //           })
        //       }
        //     }
        //   ]
        // ],
        // [
        //   [
        //     {
        //       name: '导出',
        //       click: () => {
        //         materialCategoryTemplateExcel({}, `${this.$route.meta.title}`)
        //           .then(res => {
        //             this.$message({
        //               message: '下载成功',
        //               type: 'success'
        //             })
        //           })
        //           .catch(err => {
        //             this.$message.error('下载失败')
        //           })
        //       }
        //     }
        //   ]
        // ]
      ],
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      }, // 关闭新增弹窗

      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      options: [
        {
          value: '选项1',
          label: '1'
        },
        {
          value: '选项2',
          label: '2'
        },
        {
          value: '选项3',
          label: '3'
        },
        {
          value: '选项4',
          label: '4'
        },
        {
          value: '选项5',
          label: '5'
        }
      ],
      diaLogForm: {
        id: null,
        name: '',
        number: '',
        model: '',
        volume: '',
        type: ''
      },
      showDialogForm: false,
      dataList: [],
      screenForm: {
        model: '',
        name: '',
        number: '',
        type: '',
        volume: ''
      },
      type: null,
      distList: [],
      rules: {
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        name: [{ required: true, message: '请选择名称', trigger: 'blur' }],
        model: [{ required: true, message: '请输入型号', trigger: 'blur' }],
        number: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        volume: [
          {
            required: true,
            message: '请输入体积',
            type: 'number',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    getDistList({ sysDictEnum: 'MACHINE_CONFIGURE' }).then(res => {
      this.distList = res.data
      console.log(res, 123)
    })
  },
  methods: {
    // 列表请求函数
    getList(...p) {
      this.recordSelected = []
      return getMachineLlistV2(...p)
    },
    // 列表导出函数
    exportList: exportMachineLlistV2,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    operation() {
      return (h, { row, index, column }) => {
        return (
          <div class="operation-btns">
            {this.$checkBtnRole('edit', this.$route.meta.roles) ? (
              <el-button type="text" class="textColor" onClick={() => this.editFn(row.id, row)}>
                编辑
              </el-button>
            ) : null}
            {this.$checkBtnRole('del', this.$route.meta.roles) ? (
              <el-popconfirm
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                title="内容确定删除吗？"
                onOnConfirm={() => this.hanleDeleteAll(row.id)}
              >
                <el-button slot="reference" type="text" class="textColor el-popover-left">
                  删除
                </el-button>
              </el-popconfirm>
            ) : null}
          </div>
        )
      }
    },
    handleClose() {
      this.addOff(() => {
        this.visible = false
      })()
    },
    editFn(id, row) {
      this.type = 2
      this.diaLogForm = {
        id,
        name: row.name,
        number: row.number,
        model: row.model,
        volume: row.volume,
        type: row.type
      }
      this.showDialogForm = true
    },
    resetForm(formName) {
      this.$refs.diaLogForm.resetFields()
    },
    hanleInfo() {
      console.log(this.diaLogForm)
      this.$refs.diaLogForm.validate(valid => {
        if (valid) {
          if (this.type === 1) {
            getMachineAdd(this.diaLogForm).then(res => {
              this.$successMsg('保存成功')
              this.showDialogForm = false
              this.resetInfo()
              this.$refs.pageRef.refreshList()
            })
          } else if (this.type === 2) {
            const params = {
              ...this.diaLogForm
            }
            getMachineEdit(params).then(res => {
              this.$successMsg('编辑成功')
              this.showDialogForm = false
              this.resetInfo()
              this.$refs.pageRef.refreshList()
            })
            this.diaLogForm.id = null
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 导入
    async handleImport(param) {
      this.importLoading = true
      const file = param.file
      console.log(file, 123)
      const formData = new FormData()
      formData.append('file', file)
      let result = await handleImport('stock/importToll', formData)
      this.importLoading = false
      this.importFileList = []
      if (result.code == 200) {
        this.$alert(result.message, '导入成功', {
          confirmButtonText: '确定'
        })
        this.$refs.pageRef.refreshList()
      } else {
        this.$alert(result.message, '导入失败', {
          confirmButtonText: '确定'
        })
      }
    },
    handleExport() {
      let screenData = {
        customerName: this.screenForm.customerName,
        freeDay: this.screenForm.freeDay,
        toll: this.screenForm.toll
      }
      downloadFiles('machine-record/export', screenData)
    },
    hanleDeleteAll(id) {
      const ids = [id]
      getMachineDel(ids).then(res => {
        this.$refs.pageRef.refreshList()
      })
    },
    resetInfo() {
      this.diaLogForm = {
        id: null,
        innerMachineName: '',
        innerMachineNumber: '',
        innerMachineType: '',
        innerMachineVolume: 2,
        orgNumber: '4564',
        outsideMachineName: '',
        outsideMachineNumber: '',
        outsideMachineType: '',
        outsideMachineVolume: 2
      }
    },
    findMachineType(val) {
      const obj = this.distList.find(value => value.dictCode === val)
      return obj ? obj.dictValue : ''
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
.import-btn {
  display: inline-block;
  margin-right: 10px;
}
</style>
