<template>
  <div class="app-container">
    <!-- 首页搜索 -->
    <el-form :model="formData" ref="formData" size="small" :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="formData.keyWord"
          placeholder="请输入关键字"
          clearable
          maxlength="50"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 列表 -->
    <el-table :data="houseList">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="typeName" label="机具名称" min-width="280" align="center" />
      <el-table-column prop="typeModelName" label="规格型号" min-width="280" align="center" />
      <el-table-column prop="totalNum" label="套装所需配件数量" width="200" align="center" />
      <el-table-column label="操作" align="center" width="310" fixed="right">
        <template v-slot="{ row }">
          <el-button size="mini" type="primary" icon="el-icon-search" @click="handleDetail(row)">查看明细</el-button>
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 弹框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" :close-on-click-modal="false">
      <!-- 表单 -->
      <el-form
        :model="dialogForm"
        ref="dialogForm"
        label-width="100px"
        :inline="true"
        size="small"
        @submit.native.prevent
      >
        <el-form-item
          label="物品类型"
          prop="parentId"
          :rules="[{ required: true, message: '请选择物品类型', trigger: 'change' }]"
          v-if="!isDetail"
        >
          <el-cascader
            v-model="dialogForm.parentId"
            placeholder="请选择物品类型"
            :options="typeOptions"
            filterable
            clearable
            @change="handleTypeOptions"
            style="width: 330px"
            v-if="!isDetail"
          />
        </el-form-item>

        <el-form-item
          ref="typeTree"
          label="选择配件"
          prop="mountingsValue"
          :rules="[{ required: true, message: '请选择配件', trigger: 'change' }]"
          v-if="!isDetail"
        >
          <el-cascader
            ref="mountingsTree"
            v-model="dialogForm.mountingsValue"
            placeholder="请选择配件"
            :options="mountingsOptions"
            :props="{ multiple: true }"
            filterable
            clearable
            @change="handleMountingsOptions"
            style="width: 330px"
          />
        </el-form-item>

        <el-form-item label=" " label-width="50px" v-if="!isDetail">
          <el-button type="primary" size="mini" @click="addDialogList" icon="el-icon-plus">添加</el-button>
        </el-form-item>

        <!-- 详情 -->
        <el-form-item label="关键字" prop="keyWord" v-if="isDetail">
          <el-input
            v-model="dialogForm.keyWord"
            placeholder="请输入关键字"
            clearable
            maxlength="50"
            @keyup.enter.native="handleSearch"
          />
        </el-form-item>
        <el-form-item v-if="isDetail">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="dialogList">
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="typeName" label="类型名称" align="center" />
        <el-table-column prop="typeModelName" label="规格型号" align="center" />
        <el-table-column prop="totalNum" label="每付所需数量" align="center">
          <template v-slot="{ row }">
            <el-input-number v-model="row.totalNum" size="mini" :min="1" v-if="!isDetail" />
            <span v-else>{{ row.totalNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" v-if="!isDetail">
          <template v-slot="{ row }">
            <el-popconfirm
              title="确认删除该数据?"
              placement="top"
              icon="el-icon-info"
              @confirm="handleDeleteDialog(row)"
            >
              <el-button size="mini" type="danger" icon="el-icon-delete" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="open = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="dialogSubmit" :loading="isLoading" v-if="!isDetail">
          保 存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDeviceTypeTree,
  addOrUpdateWhole,
  searchSelectList,
  searchSelectListById,
  deleteById,
  editRequest,
} from '@/api/store/poleConfig'
export default {
  name: 'poleConfig',
  data() {
    return {
      isLoading: false,
      showSearch: true,
      formData: {
        keyWord: '',
      },
      houseList: [],
      title: '新增',
      open: false,
      dialogForm: {
        parentId: '',
        mountingsValue: [],
        keyWord: '',
      },
      typeOptions: [],
      mountingsOptions: [],
      dialogList: [],
      selectList: [],
      isDetail: false,
      isEdit: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '',
      },
      rowId: '',
    }
  },
  created() {
    this.getList()
    getDeviceTypeTree().then(res => {
      // 处理为typeOptions需要的数据格式
      const data = res.data
      // this.typeOptions = this.getTree(data)
      // this.mountingsOptions = this.getTree(data)
      this.typeOptions = this.mountingsOptions = this.getTree(data)
    })
    // getDeviceTypeTree().then(res => {
    //   // 处理为mountingsOptions需要的数据格式
    //   const data = res.data
    //   this.mountingsOptions = this.getTree(data)
    // })
  },
  methods: {
    // 获取列表
    async getList(data = {}) {
      this.houseList = []
      this.queryParams.pageNum = data.page || 1
      this.queryParams.pageSize = data.limit || 10
      this.queryParams.keyWord = this.formData.keyWord || ''
      const res = await searchSelectList({ ...this.queryParams })
      this.houseList = res.data.result
      this.total = res.data.totalCount || 0
    },
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      const keyWord = this.formData.keyWord?.trim() || ''
      this.getList({ keyWord })
    },
    handleSearch() {
      const keyWord = this.dialogForm.keyWord?.trim() || ''
      this.getDetail({ id: this.rowId, keyWord })
    },
    // 重置
    resetQuery() {
      this.formData.keyWord = ''
      this.getList()
    },
    resetSearch() {
      this.dialogForm.keyWord = ''
      this.getDetail({ id: this.rowId })
    },
    // 新增
    handleAdd() {
      // 打开新增弹窗
      this.open = true
      this.title = '新增'
      this.isDetail = false
      this.isEdit = false
      this.dialogForm.parentId = ''
      this.dialogForm.mountingsValue = []
      this.dialogList = []
      setTimeout(() => {
        this.$refs.dialogForm.resetFields()
      }, 100)
    },
    // 详情弹框
    handleDetail(row) {
      this.rowId = row.id
      this.open = true
      this.isDetail = true
      this.title = '详情'
      this.dialogForm.keyWord = ''
      this.getDetail({ id: row.id })
    },
    // 获取详情
    async getDetail({ id, keyWord = '' }) {
      const res = await searchSelectListById({ id, keyWord })
      this.dialogList = res.rows
    },
    // 编辑
    handleEdit(row) {
      this.rowId = row.id
      this.open = true
      this.isDetail = false
      this.isEdit = true
      this.title = '编辑'
      this.dialogList = []
      this.$nextTick(() => {
        this.$refs.dialogForm.resetFields()
      })
      console.log('🚀 ~ handleEdit ~ row.id:', row.id)
      this.queryEdit(row.id)
    },

    async queryEdit(id) {
      const { data } = await editRequest({ id })
      this.dialogForm.parentId = data.typeList.fourId
      this.dialogForm.mountingsValue = data.list.map(item => {
        return [item.firstId, item.secondId, item.threeId, item.fourId]
      })
      this.dialogList = this.selectList = data.voList
    },
    // 删除
    handleDelete(row) {
      // 提示
      this.$confirm('是否确认删除该数据?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 删除
          deleteById({ id: row.id }).then(() => {
            this.getList()
            this.$message.success('删除成功')
          })
        })
        .catch(() => {
          this.$message.info('取消删除')
        })
    },
    // 选择物品类型
    handleTypeOptions(val) {
      this.dialogForm.parentId = val[3]
    },
    // 选择配件
    handleMountingsOptions(val) {
      console.log('🚀 ~ handleMountingsOptions ~ val:', val)
      this.dialogList = []
      this.dialogForm.mountingsValue = val

      let selected = []
      setTimeout(() => {
        selected = this.$refs.mountingsTree.getCheckedNodes()
        // 过滤出 level = 4 第4级的数据
        const filterSel = selected.filter(item => item.level === 4)
        this.selectList = filterSel.map(item => {
          return {
            id: item.value,
            typeName: item.pathLabels[2],
            typeModelName: item.label,
            totalNum: 1,
          }
        })
      }, 100)
    },
    // 添加
    addDialogList() {
      // 表单校验
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          this.dialogList = this.selectList
        } else {
          // 提示
          this.$message.warning('请填写完整信息')
          return false
        }
      })
    },
    // 删除
    handleDeleteDialog(row) {
      this.dialogList = this.dialogList.filter(item => item.id !== row.id)
    },
    getTree(data, level = 1) {
      return data.map(item => {
        if (item.children && item.children.length) {
          return {
            value: item.id,
            label: item.label,
            level,
            children: this.getTree(item.children, level + 1),
          }
        } else {
          return {
            value: item.id,
            label: item.label,
            level,
            disabled: level + 1 !== 5,
          }
        }
      })
    },
    // 保存
    async dialogSubmit() {
      // 表单校验
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          this.isLoading = true
          if (!this.dialogList.length) {
            this.isLoading = false
            this.$message.warning('请点击添加按钮添加数据')
            return false
          }

          const MaWholeSetDto = {
            parentId: this.dialogForm.parentId,
            wholeList: this.dialogList,
          }
          if (this.isEdit) {
            MaWholeSetDto.id = this.rowId
          }
          addOrUpdateWhole(MaWholeSetDto)
            .then(() => {
              this.isLoading = false
              this.open = false
              this.$message.success('保存成功')
              this.getList()
            })
            .catch(() => {
              this.isLoading = false
            })
        } else {
          this.isLoading = false
          this.$message.warning('请填写完整信息')
          return false
        }
      })
    },
  },
}
</script>

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