<template>
  <div class="app-container">
    <el-card class="fiche">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList">收起</right-toolbar>
          <span style="margin-bottom: 10px;color:#333333;font:14px Helvetica Neue, Helvetica, PingFang SC, Tahoma, Arial,sans-serif">所选条件:</span>
         <div  style="float: right;margin-right:1%">
            <el-button type="cyan"  icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"  style="float: ;">重置</el-button>
         </div>
         <hr  style="margin-top: 16px;">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜单名称" prop="spiProducName">
        <el-input
          v-model="queryParams.spiProducName"
          placeholder="请输入菜单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜单描述" prop="spiProducDescribe">
        <el-input
          v-model="queryParams.spiProducDescribe"
          placeholder="请输入菜单描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="spiState">
        <el-select
          v-model="queryParams.spiState"
          placeholder="菜单状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in spiStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item>
        <el-button type="cyan" 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-card>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:product:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:product:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:product:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:product:export']"
        >导出</el-button>
      </el-col> -->
	  <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange" stripe  border>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="序号" type="index" width="55" align="center" />
      <el-table-column label="菜单名称" align="center" prop="spiProducName" />
      <el-table-column label="菜单描述" align="center" prop="spiProducDescribe" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.spiState"
            active-value="00"
            inactive-value="01"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column> -->
      <el-table-column label="备注" align="center" prop="spiRemark" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:product:edit']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAttr(scope.row)"
            v-hasPermi="['system:attr:add']"
          >附加信息</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:product:remove']"
          >删除</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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜单名称" prop="spiProducName">
          <el-input v-model="form.spiProducName" placeholder="请输入菜单名称" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item label="菜单描述" prop="spiProducDescribe">
          <el-input v-model="form.spiProducDescribe" type="textarea" placeholder="请输入菜单描述" maxlength="30" show-word-limit/>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="spiState">
          <el-radio-group v-model="form.spiState">
            <el-radio
              v-for="dict in spiStateOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.spiMenuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.spiMenuCheckStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注" prop="spiRemark">
          <el-input v-model="form.spiRemark" type="textarea" placeholder="请输入内容" maxlength="100" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 菜单附加信息配置对话框 -->
    <el-dialog :title="title" :visible.sync="openAttr" width="500px" append-to-body>
      <el-form ref="attrForm" :model="attrForm" label-width="80px">
        <el-table v-loading="loading" :data="productAttrList">
          <el-table-column label="序号" type="index" width="55" align="center" />
          <el-table-column label="附加字段" align="center" prop="spaCode">
            <template slot-scope="scope">
              <el-select v-model="scope.row.spaCode" placeholder="请选择">
                <el-option
                  v-for="(item, index) in attrCodeOptions"
                  :key="index"
                  :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="deleteRow(scope.row)"
              >移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          size="mini"
          type="text"
          @click="addRow()"
        >添加</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAttrForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct,changeProductStatus,listProductAttr,addProductAttr,updateProductAttr,delProductAttr } from "@/api/system/product";
import { treeselect as menuTreeselect, productMenuTreeselect } from "@/api/system/menu";

export default {
  name: "Product",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜单信息表格数据
      productList: [],
      productAttrList: [],
      // 状态字典
      spiStateOptions: [],
      attrCodeOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openAttr: false,
	    menuExpand: false,
      menuNodeAll: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spiProducName: null,
        spiProducDescribe: null,
        spiMenuCheckStrictly: null,
        spiState: null,
        spiIsDel: null,
        spiRemark: null
      },
      // 菜单列表
      menuOptions: [],
      // 表单参数
      form: {},
      attrForm: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        spiProducName: [
          { required: true, message: "菜单名称不能为空", trigger: "blur" }
        ],
        spiState: [
          { required: true, message: "菜单状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("spi_state").then(response => {
      this.spiStateOptions = response.data;
    });
    this.getDicts("product_attr_code").then(response => {
      this.attrCodeOptions = response.data;
    });
  },
  methods: {
    /** 查询菜单信息列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    /** 根据菜单ID查询菜单树结构 */
    getProductMenuTreeselect(spiProducId) {
      return productMenuTreeselect(spiProducId).then(response => {
        this.menuOptions = response.menus;
        return response;
      });
    },
	  // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.spiMenuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openAttr = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
		    menuCheckStrictly: true,
        menuIds: [],
        spiProducId: null,
        spiProducName: null,
        spiProducDescribe: null,
        spiMenuCheckStrictly: true,
        spiState: '00',
        spiIsDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        spiRemark: null
      };
      this.attrForm = {},
	    this.menuExpand = false,
      this.menuNodeAll = false,
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.spiProducId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加菜单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const spiProducId = row.spiProducId || this.ids
      const productMenu = this.getProductMenuTreeselect(spiProducId);
      getProduct(spiProducId).then(response => {
        this.form = response.data;
        this.open = true;
        this.$nextTick(() => {
          productMenu.then(res => {
            this.$refs.menu.setCheckedKeys(res.checkedKeys);
          });
        });
        this.title = "修改菜单信息";
      });
    },
    /** 附加信息按钮操作 */
    handleAttr(row) {
      this.reset();
      const spiProducId = row.spiProducId || this.ids
      this.queryParams.scpProducId = spiProducId
      listProductAttr(this.queryParams).then(response => {
        console.log(response)
        this.productAttrList = response.rows;
        this.openAttr = true;
        this.title = "菜单附加信息配置";
      });
    },
    /** 增加节点 */
    addRow(){
      addProductAttr(this.queryParams).then(response => {
        this.msgSuccess("新增成功");
        listProductAttr(this.queryParams).then(response => {
          this.productAttrList = response.rows;
        });
      });
    },
    /** 移除节点 */
    deleteRow(rows) {
      delProductAttr(rows.spaId).then(response => {
        this.msgSuccess("移除成功");
        listProductAttr(this.queryParams).then(response => {
          this.productAttrList = response.rows;
        });
      });
    },
    // 菜单状态修改
    handleStatusChange(row) {
      let text = row.spiState === "00" ? "启用" : "停用";
      this.$confirm('确认要' + text + '"' + row.spiProducName + '"菜单吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeProductStatus(row.spiProducId, row.spiState);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.spiState = row.spiState === "00" ? "01" : "00";
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.menuIds = this.getMenuAllCheckedKeys();
        if (valid) {
          if(this.form.menuIds.length != '0'){
            if (this.form.spiProducId != null) {
              const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
              })
              updateProduct(this.form).then(response => {
                loading.close();
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch((response)=>{
                loading.close();
              });
            } else {
              const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
              })
              this.form.menuIds = this.getMenuAllCheckedKeys();
              addProduct(this.form).then(response => {
                loading.close();
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch((response)=>{
                loading.close();
              });
            }
          }else{
            this.$message({
              message: '请选择菜单菜单',
              type: 'warning'
            });
            return;
          }
        }
      });
    },
    /** 附加信息提交按钮 */
    submitAttrForm() {
      const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
            })
      updateProductAttr(this.productAttrList).then(response => {
        loading.close();
        this.msgSuccess("修改成功");
        this.openAttr = false;
        this.getList();
      }).catch((response)=>{
          loading.close();
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const spiProducIds = row.spiProducId || this.ids
      const spiProducName = row.spiProducName;
      this.$confirm('是否确认删除菜单名称为"' + spiProducName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProduct(spiProducIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消删除",
           
          });
        }); 
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/product/export', {
        ...this.queryParams
      }, `system_product.xlsx`)
    }
  }
};
</script>