<template>
  <!-- 类型管理 -->
  <div class="app-container" id="toolsType">
    <el-row :gutter="20">
      <!--树数据-->
      <el-col :span="5" :xs="24">
        <el-card shadow="always">
          <div slot="header">
            <span style="font-weight: 800">标准配置清单</span>
          </div>
          <!-- card body -->
          <div class="head-container">
            <el-input
              v-model="configName"
              placeholder="请输入类型名称"
              clearable
              maxlength="50"
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container" style>
            <el-tree
              style="height: 700px; overflow: scroll"
              :data="treeOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            >
              <span
                class="custom-tree-node"
                slot-scope="{ node, data }"
                @mousemove="onMousemove(data)"
                @mouseleave="onMouseleave()"
              >
                <span v-if="isMousemoveId === data.id && node.label.length > 5">
                  {{ node.label.slice(0, 3) + '...' }}
                </span>
                <span v-else>{{ node.label }}</span>

                <span class="btn-items" v-if="isMousemoveId === data.id">
                  <el-button
                    v-if="node.level == 1"
                    type="text"
                    size="mini"
                    icon="el-icon-plus"
                    @click.stop="() => appendTreeNode(data)"
                  ></el-button>
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-edit-outline"
                    style="color: #67c23a"
                    v-if="data.id !== 0"
                    @click.stop="() => editTreeNode(data)"
                  ></el-button>
                  <el-button
                    type="text"
                    size="mini"
                    icon="el-icon-delete"
                    style="color: #f56c6c"
                    v-if="data.id !== 0 && node.level !== 1"
                    @click.stop="() => removeTreeNode(data)"
                  ></el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-card>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="关键字" prop="keyWord">
            <el-input
              v-model="queryParams.keyWord"
              placeholder="请输入关键字"
              clearable
              style="width: 240px"
              @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-button type="primary" icon="el-icon-plus" size="mini" @click="addConfig">新增配置</el-button>
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">
              导出数据
            </el-button>
          </el-form-item>
        </el-form>

        <el-card shadow="always" :body-style="{ padding: '20px' }">
          <div slot="header">
            <span>配置明细清单</span>
          </div>
          <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
          <!-- card body -->
          <el-table v-loading="loading" :data="tableList" border>
            <el-table-column
              label="序号"
              align="center"
              width="80"
              type="index"
              :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"
            ></el-table-column>
            <el-table-column
              v-for="(item, index) in tabColumns"
              :label="item.label"
              :key="index"
              :prop="item.prop"
              align="center"
              show-overflow-tooltip
            >
              <template v-slot="scope" v-if="item.prop == 'num'">
                <span v-if="!scope.row.isEdit">{{ scope.row.num }}</span>
                <el-input-number
                  v-else
                  v-model="scope.row.num"
                  :precision="0"
                  :step="1"
                  :min="0"
                  :max="9999"
                  :controls="false"
                  style="width: 100px"
                  @blur="handleBlur(scope.row)"
                ></el-input-number>
              </template>
              <template v-slot="scope" v-else-if="item.prop == 'remark'">
                <span v-if="!scope.row.isEdit">{{ scope.row.remark }}</span>
                <el-input
                  v-else
                  v-model="scope.row.remark"
                  style="width: 100px"
                  maxlength="150"
                  @blur="handleBlur(scope.row)"
                ></el-input>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="180">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  style="color: #f56c6c"
                  @click="handleDelete(scope.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-card>
      </el-col>
    </el-row>

    <!-- 新增配置 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="formRules" label-width="120px">
        <el-form-item label="配置名称" prop="configId">
          <el-select v-model="form.configId" placeholder="请选择配置名称" filterable clearable style="width: 100%">
            <el-option
              v-for="item in configOptions"
              :key="item.configId"
              :label="item.configName"
              :value="item.configId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物资名称" prop="typeIds">
          <el-cascader
            v-model="form.typeIds"
            :options="typeOptions"
            :props="{ value: 'typeId', label: 'typeName' }"
            @change="changeType"
            style="width: 100%"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="规格型号" prop="typeModel">
          <el-select v-model="form.typeModel" multiple placeholder="请选择规格型号" clearable style="width: 100%">
            <el-option v-for="item in typeModelOptions" :key="item.typeId" :label="item.name" :value="item.typeId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <template>
          <el-button type="primary" @click="submitForm">添 加</el-button>
          <el-button @click="closeForm">关 闭</el-button>
        </template>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="configVisible" :title="configTitle" width="40%">
      <el-form ref="configForm" :model="configForm" :rules="configRules" label-width="120px">
        <el-form-item label="配置名称" prop="configName">
          <el-input v-model="configForm.configName" placeholder="请输入配置名称" clearable maxlength="200" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfig">确 定</el-button>
        <el-button @click="configVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  getConfigTreeSelect,
  addConfig,
  editConfig,
  delConfig,
  getListByConfigId,
  getConfigList,
  getEquipmentThreeType,
  getMaTypeOpt,
  addConfigDetails,
  editConfigDetails,
  delConfigDetails
} from '@/api/ma/base'

export default {
  name: 'MechEquipConfigMgmt/index',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      configName: '',
      // 总条数
      total: 0,
      isAddTree: false, // 新增配置
      configTitle: '新增配置',
      configVisible: false,
      configForm: {
        parentId: '', // 上级类型
        configName: '' // 配置名称
      },
      configRules: {
        configName: [{ required: true, message: '请输入配置名称', trigger: 'blur' }]
      },
      tabColumns: [
        { label: '仓库信息', prop: 'houseName' },
        { label: '施工类型', prop: 'constructionType' },
        { label: '物资类型', prop: 'materialType' },
        { label: '物资名称', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModelName' },
        { label: '计量单位', prop: 'unit' },
        { label: '数量', prop: 'num' },
        { label: '备注', prop: 'remark' }
      ],
      configOptions: [],
      // 物资名称
      typeOptions: [],
      // 规格型号
      typeModelOptions: [],
      // 树选项
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      treeOptions: undefined,
      treeTemp: [],
      treeTempTwo: [],
      //列表数据
      tableList: undefined,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: '',
      // 表单参数
      form: {
        configId: '', // 配置名称id
        typeIds: [], // 物资名称
        typeModel: [] // 规格型号
      },
      formRules: {
        configId: [{ required: true, message: '请选择配置名称', trigger: 'change' }],
        typeIds: [{ required: true, message: '请选择物资名称', trigger: 'change' }],
        typeModel: [{ required: true, message: '请选择规格型号', trigger: 'change' }]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        level: 1,
        configId: '',
        keyWord: ''
      },
      isMousemoveId: null
    }
  },
  watch: {
    // 根据名称筛选树
    configName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getTreeData()
    this.getList()
  },
  methods: {
    // 获取树数据
    getTreeData() {
      try {
        getConfigTreeSelect().then(res => {
          this.treeOptions = res.data
        })
      } catch (error) {
        console.log('🚀 ~ getTreeData ~ error:', error)
        this.treeOptions = []
      }
    },
    /** 查询列表 */
    getList() {
      try {
        this.loading = true
        console.log('🚀 ~ getList ~ this.queryParams:', this.queryParams)
        getListByConfigId(this.queryParams).then(res => {
          this.tableList = res.data.rows
          if (this.tableList.length > 0) {
            this.tableList.forEach(item => {
              item.isEdit = this.$set(item, 'isEdit', false)
            })
          }
          this.total = res.data.total || 0
          this.loading = false
        })
      } catch (error) {}
    },
    // 物资名称下拉
    getConfigOpt() {
      try {
        getConfigList().then(res => {
          this.configOptions = res.data
        })
      } catch (error) {
        console.log('🚀 ~ getConfigOpt ~ error:', error)
        this.configOptions = []
      }
    },
    async getTypeOptions() {
      try {
        const res = await getEquipmentThreeType()
        console.log('🚀 ~ getTypeOptions ~ res:', res)
        this.typeOptions = res.data
      } catch (error) {
        console.log('🚀 ~ getTypeOptions ~ error:', error)
        this.typeOptions = []
      }
    },
    // 筛选节点 - 左侧树
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件 - 左侧树
    async handleNodeClick(data, node) {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        level: data.level,
        configId: data.id
      }
      if (data.level === 2) {
        this.form.configId = data.id
      }
      this.getList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.queryParams.level = 1
      this.queryParams.configId = undefined
      this.queryParams.keyWord = undefined
      this.getList()
    },
    // 新增配置
    addConfig() {
      this.open = true
      this.title = '新增配置'
      this.form.configId = this.form.configId || ''
      this.form.typeIds = []
      this.form.typeModel = []
      this.getConfigOpt()
      this.getTypeOptions()
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    // 物资名称变更
    changeType(val) {
      console.log('🚀 ~ changeType ~ val:', val)
      this.form.typeModel = []
      this.typeModelOptions = []
      if (val.length > 0) {
        const params = {
          typeId: val[val.length - 1]
        }
        getMaTypeOpt(params).then(res => {
          this.typeModelOptions = res.data
        })
      }
    },
    // 数量/备注变更
    handleBlur(row) {
      try {
        row.isEdit = false
        const params = {
          detailsId: row.detailsId,
          num: row.num,
          remark: row.remark
        }
        editConfigDetails(params).then(res => {
          this.$modal.msgSuccess('修改成功')
        })
      } catch (error) {
        console.log('🚀 ~ handleBlur ~ error:', error)
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      row.isEdit = !row.isEdit
    },
    closeForm() {
      this.$refs['form'].resetFields()
      this.open = false
      this.getTreeData()
      this.getList()
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form, '提交参数---')
      this.$refs['form'].validate(valid => {
        if (valid) {
          const loading = this.$loading()
          try {
            const params = {
              configId: this.form.configId,
              typeIds: this.form.typeModel
            }
            console.log('🚀 ~ 提交 params:', params)
            addConfigDetails(params)
              .then(res => {
                this.$modal.msgSuccess('新增成功')
                this.form.typeModel = []
                this.getList()
                this.getTreeData()
                this.open = false
                loading.close()
              })
              .catch(err => {
                console.log('🚀 ~ addConfigDetails ~ err:', err)
                loading.close()
              })
          } catch (error) {
            console.log('🚀 ~ error:', error)
            loading.close()
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log('🚀 ~ handleDelete ~ row:', row)
      const detailsId = row.detailsId
      this.$modal
        .confirm('是否确认删除数据项？')
        .then(() => {
          const loading = this.$loading()
          delConfigDetails({ detailsId })
            .then(() => {
              this.$modal.msgSuccess('删除成功')
              this.getList()
              loading.close()
            })
            .catch(err => {
              console.log('🚀 ~ handleDelete ~ err:', err)
              loading.close()
            })
        })
        .catch(() => {})
    },
    /** 导出按钮作 */
    handleExport() {
      let queryTemp = this.queryParams
      this.download(
        '/material/standardConfig/export',
        {
          ...queryTemp
        },
        `机械设备标准配置清单_${new Date().getTime()}.xlsx`
      )
    },
    /* 树节点增加 */
    appendTreeNode(data) {
      this.configVisible = true
      this.isAddTree = true
      this.configTitle = '新增配置'
      this.configForm.parentId = data.id
      this.configForm.configName = ''
      this.$nextTick(() => {
        this.$refs['configForm'].clearValidate()
      })
    },
    /* 树节点删除 */
    removeTreeNode(data) {
      console.log(data, '删除时的数据源--')
      const configId = data.id
      this.$modal
        .confirm('是否确认删除数据项？')
        .then(() => {
          const loading = this.$loading()
          delConfig({ configId })
            .then(() => {
              this.$modal.msgSuccess('删除成功')
              this.getTreeData()
              this.resetQuery()
              loading.close()
            })
            .catch(err => {
              loading.close()
            })
        })
        .catch(() => {})
    },
    /* 树节点修改 */
    editTreeNode(data) {
      this.configVisible = true
      this.isAddTree = false
      this.configTitle = '编辑配置'
      this.configForm.parentId = data.parentId
      this.configForm.configId = data.id
      this.configForm.configName = data.label
      // 清除校验
      this.$nextTick(() => {
        this.$refs['configForm'].clearValidate()
      })
    },
    onMousemove(data) {
      this.isMousemoveId = data.id
    },
    onMouseleave() {
      this.isMousemoveId = null
    },
    // 新增编辑配置
    submitConfig() {
      this.$refs['configForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading()
          console.log(this.configForm, '提交参数---')
          try {
            if (this.isAddTree) {
              // 新增
              addConfig(this.configForm).then(async res => {
                this.$modal.msgSuccess('新增成功')
                this.getTreeData()
                this.configVisible = false
                loading.close()
              })
            } else {
              // 编辑
              editConfig(this.configForm).then(res => {
                this.$modal.msgSuccess('编辑成功')
                this.getTreeData()
                this.configVisible = false
                loading.close()
              })
            }
          } catch (error) {
            loading.close()
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .btn-items .el-button + .el-button {
  margin-left: 6px;
}
.btn-items {
  margin-left: 4px;
  .el-button--text {
    font-size: 16px;
  }
}
::v-deep .el-tree .el-tree-node__expand-icon.expanded {
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
}
::v-deep .el-tree .el-icon-caret-right:before {
  content: '\e783';
  font-size: 16px;
}
::v-deep .el-tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
  content: '\e781';
  font-size: 16px;
  color: #1890ff;
}

::v-deep .el-tree-node__content > .el-tree-node__expand-icon {
  color: #1890ff !important;
}
::v-deep .el-tree-node__expand-icon.is-leaf {
  color: transparent !important;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #8decf1;
}

// 表格内文字样式
::v-deep .el-table {
  font-size: 14px;

  th {
    font-weight: 500;
    color: #303133;
  }

  td {
    color: #606266;
  }
}

// 按钮文字样式
::v-deep .el-button {
  font-size: 14px;

  &--text {
    font-size: 13px;
  }
}

// 树节点文字样式
::v-deep .el-tree-node__label {
  font-size: 14px;
  color: #606266;
}

// 搜索框文字样式
::v-deep .el-input--small {
  .el-input__inner {
    font-size: 13px;

    &::placeholder {
      font-size: 13px;
      color: #c0c4cc;
    }
  }
}
</style>
