<template>
  <div class="app-container">
    <div class="option-container">
      <el-button type="primary" @click="handleAddCategory()"
                 icon="el-icon-plus"
                 v-hasPermi="['basic:category:add']"
                 plain>添加类型</el-button>
    </div>

    <el-table :data="list" :row-style="{ height: '20px' }" border>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table style="width: 100%; padding-left: 50px" :data="props.row.childrenCategory">
            <el-table-column label="图标">
              <template slot-scope="scope">
                <el-image
                  class="icon"
                  :src="scope.row.icon"
                  fit="fit"
                >
                  <div slot="error">
                    <img src="../../../assets/images/image_placeholder.png" />
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="categoryName">
            </el-table-column>
            <el-table-column label="排序">
              <template slot-scope="scope">
                <el-link
                  class="el-icon-top"
                  @click="handleChildSorting(scope.row, props.$index, scope.$index - 1, true)"
                  v-show="scope.$index > 0"
                ></el-link>
                <el-link
                  class="el-icon-bottom"
                  @click="handleChildSorting(scope.row, props.$index, scope.$index + 1, false)"
                  v-show="
                    props.row.childrenCategory != null && (scope.$index + 1 < props.row.childrenCategory.length)
                  "
                ></el-link>
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEditChildCategory(scope.row)"
                  v-hasPermi="['basic:category:edit']"
                  >编辑
                </el-button>
                <el-button
                  type="text"
                  icon="el-icon-close"
                  @click="closeCategory(scope.row)"
                  v-hasPermi="['basic:category:state']"
                  >{{ scope.row.isEnable == 0 ? "开启" : "关闭" }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column label="图标" prop="icon">
        <template slot-scope="scope">
          <el-image class="icon" :src="scope.row.icon" fit="fit">
            <div slot="error">
              <img src="../../../assets/images/image_placeholder.png" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="categoryName"></el-table-column>
      <el-table-column label="评价维度">
        <template slot-scope="scope">
          <template
            v-if="
              scope.row.dimensionList &&
              scope.row.dimensionList.length > 0">
            <span
              v-for="(item, index) in scope.row.dimensionList"
              :key="index">
              {{ item.name }}
              <span
                v-if="
                  (index + 1 < scope.row.dimensionList.length) &&
                  (scope.row.dimensionList[index + 1].name != '')">、
              </span>
            </span>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="排序">
        <template slot-scope="scope">
          <el-link
            class="el-icon-top"
            v-show="scope.$index > 0"
            @click="handleParentSorting(scope.row, scope.$index - 1)"
          ></el-link>
          <el-link
            class="el-icon-bottom"
            @click="handleParentSorting(scope.row, scope.$index + 1)"
            v-show="scope.$index + 1 < list.length"
          ></el-link>
        </template>
      </el-table-column>
      <el-table-column label="首页展示" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.indexShow"
            :active-value="1"
            :inactive-value="0"
            @change="handleIndexShow(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        width="240"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleEditCategory(scope.row)"
            v-hasPermi="['basic:category:editChild']"
            >编辑
          </el-button>
          <el-button
            type="text"
            icon="el-icon-plus"
            @click="handleAddChildCategory(scope.row)"
            v-hasPermi="['basic:category:addChild']"
            >添加子类型
          </el-button>
          <el-button
            type="text"
            icon="el-icon-close"
            @click="closeCategory(scope.row)"
            v-hasPermi="['basic:category:state']"
            >{{ scope.row.isEnable == 0 ? "开启" : "关闭" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="editCategoryTitle"
      :visible.sync="editCategoryVisible"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :rules="categoryRules" :model="categoryForm" label-width="100px">
        <el-form-item label="图标" class="form-item">
          <Upload @imageUrl="setCategoryImageUrl" :url="categoryForm.icon"  />
        </el-form-item>
        <el-form-item label="名称" class="form-item" prop="categoryName">
          <el-row>
            <el-col :span="18">
              <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称"/>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="评价维度" class="form-item">
          <el-row v-if="categoryForm.dimensionList === undefined || categoryForm.dimensionList === null || categoryForm.dimensionList.length === 0">
            <i
              class="el-icon-circle-plus-outline"
              type="normal"
              style="font-size: 20px; color: #46A6FF; margin-right: 5px"
              @click="addDimension"
            ></i>
          </el-row>
          <el-row v-else
            v-for="(item, index) in categoryForm.dimensionList"
            :key="index"
            class="mydata-row"
          >
            <el-form-item label="" >
              <el-col :span="18">
                <el-input v-model="item.name" placeholder="请输入维度名称"></el-input>
              </el-col>

              <i
                class="el-icon-circle-plus-outline"
                type="normal"
                style="font-size: 20px; color: #46A6FF; margin: 0 5px"
                @click="addDimension"
              ></i>
              <i
                class="el-icon-remove-outline"
                type="danger"
                style="font-size: 20px; color: #F56C6C; margin-right: 5px"
                @click="delDimension(index)"
              ></i>
            </el-form-item>
          </el-row>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="editChildCategoryTitle"
      :visible.sync="editChildCategoryVisible"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :rules="categoryRules" :model="childCategoryForm" label-width="100px">
        <el-form-item label="图标" class="form-item">
          <Upload @imageUrl="setChildCategoryImageUrl" :url="childCategoryForm.icon"  />
        </el-form-item>
        <el-form-item label="名称" class="form-item" prop="categoryName">
          <el-row>
            <el-col :span="18">
              <el-input v-model="childCategoryForm.categoryName" placeholder="请输入分类名称"/>
            </el-col>
          </el-row>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelChild">取 消</el-button>
        <el-button type="primary" @click="submitChildForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>


</template>
<script>
import Upload from "@/components/Upload/index.vue";
import { submit, categoryList, submitChild, updateEnable, updateSorting, updateIndexShow } from "@/api/basic/category";
export default {
  components: { Upload },
  data() {
    return {
      bizType : 1,
      list: [],
      form: {
        icon: "",
        parentId: "",
      },
      dialogTitle: "",
      open: false,
      editor: false,
      editCategoryTitle: "添加类型",
      editCategoryVisible: false,
      categoryForm: {
        icon: "",
        categoryName: "",
        bizType: this.bizType,
        dimensionList: [
          {
            dimensionId: "",
            name: "",
            delFlag: 0
          },
        ],
      },
      categoryRules: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "change" },
        ],
      },

      editChildCategoryTitle: "添加子类型",
      editChildCategoryVisible: false,
      childCategoryForm: {
        icon: "",
        categoryName: "",
        parentId: null,
        bizType: this.bizType,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      categoryList(this.bizType).then(res => {
        this.list = res.data
      }).catch(err => {
        this.$message.error("获取列表失败！");
        console.log(err)
      })
    },
    submitForm() {
      if (this.categoryForm.dimensionList.length == 0) {
        this.$message.error("评价维度不能为空！");
        return false;
      }
      if (this.isNull(this.categoryForm.categoryName)) {
        this.$message.error("分类名称不能为空！");
        return false;
      }
      for (let i = 0; i < this.categoryForm.dimensionList.length; i++) {
        let item = this.categoryForm.dimensionList[i]
        if (this.isNull(item.name)) {
          this.$message.error("评价维度不可为空！");
          return false;
        }
      }
      let that = this;
      submit(this.categoryForm).then(res => {
        console.log(res)
        this.$message.success("操作成功")
        that.editCategoryVisible =false;
        that.getList();
      }).catch(err => {
        console.log(err)
      })
    },
    submitChildForm() {
      if (this.isNull(this.childCategoryForm.categoryName)) {
        this.$message.error("分类名称不能为空！");
        return false;
      }
      let that = this;
      submitChild(this.childCategoryForm).then(res => {
        console.log(res)
        this.$message.success("操作成功")
        that.editChildCategoryVisible = false;
        that.getList();
      }).catch(err => {
        console.log(err)
      })
    },
    isNull (str) {
      // var str = str.replace(/(^\s*)|(\s*$)/g, '');//去除空格;
      if (str === '' || str === undefined || str === null) {
        console.log(str)
        return true;
      } else {
        return false;
        // console.log('非空');
      }
    },
    handleAddCategory() {
      this.editCategoryTitle = "添加分类";
      this.editCategoryVisible = true;
      this.categoryForm = {
        icon: "",
        categoryName: "",
        bizType: this.bizType,
        dimensionList: [
          {
            dimensionId: "",
            name: "",
            delFlag: 0
          },
        ],
      }
    },
    // 编辑
    handleEditCategory(data) {
      var json = JSON.stringify(data)
      this.categoryForm = JSON.parse(json)
      this.editCategoryTitle = "编辑分类";
      this.editCategoryVisible = true;
    },
    handleAddChildCategory(row) {
      this.childCategoryForm = {
          icon: "",
          categoryName: "",
          parentId: null,
          bizType: this.bizType,
      },
      this.childCategoryForm.parentId = row.categoryId;
      this.editChildCategoryTitle = "添加子分类"
      this.editChildCategoryVisible = true;
    },
    handleEditChildCategory(row) {
      var json = JSON.stringify(row)
      this.childCategoryForm = JSON.parse(json)
      // this.childCategoryForm = row;
      this.editChildCategoryTitle = "编辑子分类"
      this.editChildCategoryVisible = true;
    },
    handleIndexShow(row) {
      let self = this;
      let text = row.indexShow === 0 ?  "隐藏" : "展示";
      this.$confirm('确认要在首页【' + text + '】【' + row.categoryName + '】分类吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(res => {
        updateIndexShow(row.categoryId, row.indexShow).then(res => {
          self.$message.success(text + "成功");
        }).catch(err => {
          console.log(err)
          row.indexShow = row.indexShow === 0 ? 1 : 0;
        })
      }).catch(err => {
        row.indexShow = row.indexShow === 0 ? 1 : 0;
      });
    },
    handleChildSorting(row, parentIndex, childIndex, isTop) {
      var item = this.list[parentIndex].childrenCategory[childIndex];
      console.log(row, item)
      if(row.sorting && row.sorting == item.sorting) {  // 防止重复
        if(isTop) {
          item.sorting = item.sorting - 1
        } else {
          row.sorting = item.sorting + 1
        }
      }
      const form = [
        {
          categoryId: row.categoryId,
          sorting: item.sorting == null ? 1 : item.sorting,
        },
        {
          categoryId: item.categoryId,
          sorting: row.sorting == null ? 1 : row.sorting,
        },
      ];
      updateSorting(form).then((response) => {
        if (response.code === 200) {
          this.getList();
        }
      });
    },
    handleParentSorting(row, index, isChild) {
      console.log("---------", this.list)
      var item = this.list[index];
      const form = [
        {
          categoryId: row.categoryId,
          sorting: item.sorting == null ? 1 : item.sorting,
        },
        {
          categoryId: item.categoryId,
          sorting: row.sorting == null ? 1 : row.sorting,
        },
      ];
      updateSorting(form).then((response) => {
        if (response.code === 200) {
          this.getList();
        }
      });
    },

    /**上传图片成功**/
    handleImageSuccess(res, file) {
      console.log(res);
      this.form.icon = res.result;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    closeCategory(row) {
      const self = this;
      console.log(row);
      var title = "";
      if (row.isEnable) {
        title = "关闭类型";
      } else {
        title = "开启类型";
      }

      this.$confirm(
        "确定要" + title + "： " + row.categoryName + " 吗？",
        title,
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(function () {
          updateEnable({
            categoryId: row.categoryId,
            isEnable: row.isEnable == 0 ? 1 : 0,
          }).then(() => {
            self.getList();
            self.$message.success(title + "成功");
          });
        }).catch(function () {});
    },
    cancel() {
      this.editCategoryVisible = false;
    },
    cancelChild() {
      this.editChildCategoryVisible = false;
    },
    // 表单重置
    reset() {
      this.form = {
        icon: "",
        parentId: "",
      };
      this.resetForm("form");
    },
    setCategoryImageUrl(val) {
      this.categoryForm.icon = val
      console.log('类型图标上传成功', val)
    },
    setChildCategoryImageUrl(val) {
      this.childCategoryForm.icon = val
      console.log('类型图标上传成功', val)
    },
    addDimension() {
      this.categoryForm.dimensionList.push({
        dimensionId: "",
        name: "",
        delFlag: 0
      })
    },
    delDimension(index) {
      // let itemCount = 0;
      // this.categoryForm.dimensionList.map(function (item, index) {
      //   if (item.delFlag === 0) {
      //     itemCount++;
      //   }
      // });
      // if (itemCount <= 1) {
      //   this.$message.error("不可全部删除！");
      //   return;
      // }
      this.categoryForm.dimensionList.splice(index,1)
      console.log(this.categoryForm.dimensionList.length)
    },
  },
};
</script>

<style scoped lang="scss">
img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
.option-container {
  display: flex;
  padding-bottom: 20px;
  justify-content: flex-end;
}
.icon-container {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
}
.icon {
  width: 60px;
  height: 60px;
  margin-right: 10px;
}

.mydata-row {
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>
