<!-- eslint-disable eqeqeq -->
<!-- eslint-disable eqeqeq -->
<template>
  <div class="wrap card">
    <el-form :inline="true" size="mini" v-enter-submit="getList">
      <el-form-item label="中文名">
        <el-input
          clearable
          style="width: 120px"
          v-model="searchForm.cnname"
          placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="英文名">
        <el-input
          clearable
          style="width: 120px"
          v-model="searchForm.enname"
          placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="SKU属性">
        <el-select
          style="width: 120px"
          v-model="searchForm.skuProperty"
          clearable
          value-key=""
          placeholder="请选择">
          <el-option label="是" :value="true"></el-option>
          <el-option label="否" :value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="addDialog(1)">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="deleteSection()">删除</el-button>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px">
        <el-button type="primary" @click="importExcel">导入</el-button>
      </el-form-item>
    </el-form>
    <div class="table_wrap">
      <my-table
        :sourceData="userData"
        ref="multipleTable"
        :selection="true"
        :tableColumns="tableColumns"
        @selectionChange="selectionChange"
        @currentChange="currentTabFn"></my-table>
    </div>
    <div class="pagination">
      <pagination
        layout="sizes, total, prev, pager, next, jumper"
        background
        :total="paginationOptions.total"
        :page-size="paginationOptions.pageSize"
        :current-page="paginationOptions.currentPage"
        @size-change="sizeChange"
        @current-change="onCurrentChange" />
    </div>

    <!-- 弹出层 -->
    <el-dialog
      custom-class="custom-dialog"
      :close-on-click-modal="false"
      :title="is_title == 1 ? '新增' : '编辑'"
      :visible.sync="dialogVisible"
      width="800px">
      <el-form
        label-position="right"
        label-width="100px"
        size="mini"
        :model="addcurrencyform"
        :rules="addrules"
        ref="addcurrencyform">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="中文名" prop="cnname">
              <el-input
                style="width: 100%"
                v-model="addcurrencyform.cnname"
                placeholder="请输入中文名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="英文名" prop="enname">
              <el-input
                style="width: 100%"
                v-model="addcurrencyform.enname"
                placeholder="请输入英文名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="sku属性" prop="skuProperty">
              <div style="width: 100%">
                <el-radio v-model="addcurrencyform.skuProperty" :label="true">
                  是
                </el-radio>
                <el-radio v-model="addcurrencyform.skuProperty" :label="false">
                  否
                </el-radio>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="多选" prop="multi">
              <div style="width: 100%">
                <el-radio v-model="addcurrencyform.multi" :label="true">
                  是
                </el-radio>
                <el-radio v-model="addcurrencyform.multi" :label="false">
                  否
                </el-radio>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序序号" prop="sort">
              <el-input
                style="width: 100%"
                v-model.number="addcurrencyform.sort"
                placeholder="请输入数字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <p class="pop-p">
          属性SKU
          <span class="pop-p-but">
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="selectProp">
              选择属性
            </el-button>
          </span>
        </p>
        <div style="min-height: 40px; background: #fff">
          <div
            v-for="(item, index) in selectProps"
            class="variants"
            v-show="item.children.length > 0"
            :key="index">
            <div class="title">{{ `${item.name}(${item.code})` }}</div>
            <ul class>
              <li
                v-for="g in item.children"
                :key="g.id"
                :style="{
                  background: g.bgColor,
                  color: g.fontColor
                }">
                {{ g.cnname }}
                <i
                  class="el-icon-close"
                  @click="optionDelete(index, g.code)"></i>
              </li>
            </ul>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="dialogVisible = false"
          size="mini"
          style="width: 130px">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="addCurrency()"
          size="mini"
          style="width: 130px">
          确认
        </el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="propDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      title="选择属性">
      <div class="product-prop">
        <div
          class="product-prop_item"
          v-for="(item, index) in productPropertiesMap"
          :key="index">
          <div class="prop-label">
            <span>{{ `${item.code}(${item.name})` }}</span>
          </div>
          <el-checkbox
            :indeterminate="typeof propMapIsCheckedAll(item) === 'number'"
            :value="propMapIsCheckedAll(item) === true"
            @input="propMapOnCheckAllInput(item, $event)">
            全选
          </el-checkbox>
          <el-checkbox-group v-model="checkedProps" class="prop-checkbox">
            <el-checkbox
              v-for="(e, index1) in item.children"
              :key="index1"
              :label="e.id"
              :style="{ background: e.bgColor, color: e.fontColor }">
              {{ e.cnname }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="propDialogVisible = false" size="small">
          取消
        </el-button>
        <el-button @click="submitProp" type="primary" size="small">
          确认
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from '../../common/api/axios'
import MyTable from '@/common/components/base/tableView.vue'
export default {
  name: 'system_sku-sort',
  components: {
    MyTable
  },
  data() {
    return {
      propDialogVisible: false,
      checkedProps: [],
      productProperties: [],
      is_title: 1,
      userData: [],
      searchForm: {},
      selection: [],
      dialogVisible: false,
      addcurrencyform: {
        id: '',
        cnname: '',
        enname: '',
        sort: '',
        skuProperty: false,
        multi: false,
        enable: true
      },
      addcurrencyform2: null,
      formId: null,
      addrules: {
        cnname: [
          {
            required: true,
            message: '请输入中文名',
            trigger: 'blur'
          }
        ],
        enname: [
          {
            required: true,
            message: '请输入英文名',
            trigger: 'blur'
          }
        ]
      },
      paginationOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      selectProps: []
    }
  },
  computed: {
    tableColumns() {
      return [
        { label: '中文名', key: 'cnname', align: 'left' },
        { label: '英文名', key: 'enname', align: 'left' },
        {
          label: 'sku属性',
          key: 'skuProperty',
          render: (item) => (
            <div style="font-size: 20px">
              {item.skuProperty === true ? (
                <i style="color: green" class="el-icon-success"></i>
              ) : (
                <i style="color: red" class="el-icon-error"></i>
              )}
            </div>
          )
        },
        {
          label: '多选',
          key: 'multi',
          render: (item) => (
            <div style="font-size: 20px">
              {item.multi === true ? (
                <i style="color: green" class="el-icon-success"></i>
              ) : (
                <i style="color: red" class="el-icon-error"></i>
              )}
            </div>
          )
        },
        {
          label: '排列序号',
          key: 'sort',
          width: 80,
          align: 'right'
        },
        {
          label: '状态',
          key: 'enable',
          width: 80,
          render: (item) => (
            <el-switch
              onChange={(v) => this.changeDisableStatus(v, item)}
              v-model={item.enable}
              active-color="#13ce66"
              inactive-color="#ff4949"></el-switch>
          )
        },
        {
          label: '相关操作',
          width: 80,
          render: (item) => (
            <div>
              <span class="icon-view icon-edit-view" title="编辑">
                <i
                  class="el-icon-edit"
                  onClick={() => this.addDialog(2, item)}></i>
              </span>
              <span class="icon-view icon-del-view" title="删除">
                <i
                  class="el-icon-delete-solid"
                  onClick={() => this.deleteSection(item)}></i>
              </span>
            </div>
          )
        }
      ]
    },
    productPropertiesMap() {
      const properties = []
      this.productProperties.forEach((item) => {
        const prop = {
          code: item.cateCode,
          name: item.cateName,
          cnname: item.cnname,
          enname: item.enname,
          children: []
        }
        const current = properties.find((e) => e.code === item.cateCode)
        if (current) {
          current.children.push(item)
        } else {
          prop.children.push(item)
          properties.push(prop)
        }
      })
      return properties
    }
  },
  created() {
    this.getList(1)
    this.loadProductProperties()
    this.addcurrencyform2 = JSON.parse(JSON.stringify(this.addcurrencyform))
  },

  methods: {
    importExcel() {
      const input = document.createElement('input')
      input.style.display = 'none'
      input.type = 'file'
      input.click()
      input.onchange = async () => {
        const form = new FormData()
        form.append('importExcel', input.files.length > 0 ? input.files[0] : [])
        const res = await axios.post('baseProperty/importBaseProperty', form)
        console.log(res)
        if (res.code === 200) {
          this.$message.success('导入成功')
          this.getList()
        }
      }
    },
    async changeDisableStatus(v, item) {
      try {
        await this.$confirm(
          `确定将状态改为${v === false ? '禁用' : '启用'}吗?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
      } catch {
        this.$set(item, 'enable', !v)
        return
      }
      try {
        const res = await axios.get('baseProperty/changeEnable', {
          params: {
            id: item.id,
            enable: v
          }
        })
        if (res.code !== 200) return
        this.$message.success(res.message)
        this.getList()
      } catch (e) {
        console.error(e)
      }
    },
    async submitProp() {
      if (!this.checkedProps.length) {
        return this.$message.warning('请选择属性')
      }
      this.getSelectProp()
      this.propDialogVisible = false
    },
    getSelectProp() {
      const props = []
      this.productProperties.forEach((item) => {
        const obj = {
          code: item.cateCode,
          enname: item.enname,
          cnname: item.cnname,
          name: item.cateName,
          children: []
        }
        if (this.checkedProps.includes(item.id)) {
          const current = props.find((ee) => ee.code === item.cateCode)
          if (current) {
            current.children.push(item)
          } else {
            obj.children.push(item)
            props.push(obj)
          }
        }
      })
      this.selectProps = props
    },
    selectProp() {
      const ids = []
      this.selectProps.forEach((item) => {
        item.children.forEach((e) => {
          ids.push(e.id)
        })
      })
      this.checkedProps = ids
      this.propDialogVisible = true
    },
    optionDelete(index, code) {
      this.selectProps[index].children = this.selectProps[
        index
      ].children.filter((item) => item.code !== code)
    },
    propMapOnCheckAllInput(g, value) {
      if (value) {
        g.children.forEach((e) => {
          if (!this.checkedProps.some((id) => id === e.id)) {
            this.checkedProps.push(e.id)
          }
        })
      } else {
        g.children.forEach((e) => {
          const i = this.checkedProps.indexOf(e.id)
          if (i >= 0) this.checkedProps.splice(i, 1)
        })
      }
    },
    propMapIsCheckedAll(g) {
      // eslint-disable-next-line array-callback-return
      const n = g.children.filter((item) =>
        this.checkedProps.includes(item.id)
      )?.length
      if (n === 0) return false
      if (n === g.children.length) return true
      return n
    },
    async loadProductProperties() {
      try {
        const res = await axios.get('manage/rest/base/propertyValue/getAllData')
        if (res.code !== 200) return
        this.productProperties = res.data
      } catch (e) {
        console.error(e)
      }
    },
    onCurrentChange(currentPage) {
      this.paginationOptions.currentPage = currentPage
      this.getList()
    },
    sizeChange(pageSize) {
      this.paginationOptions.pageSize = pageSize
      this.getList()
    },
    currentTabFn(val) {
      if (val) this.formId = val.id
      else this.formId = null
    },
    selectionChange(selection) {
      this.selection = selection
    },
    // 修改新增
    addDialog(i, v = null) {
      if (i === 2) {
        if (v) this.formId = v.id
        if (!this.formId) {
          return this.$message('请勾选至少一条记录')
        }
        this.checkedProps = v.propertyValueIds
        this.getSelectProp()
        this.addcurrencyform = Object.assign({}, v)
      } else {
        this.$nextTick(() => {
          this.addcurrencyform = JSON.parse(
            JSON.stringify(this.addcurrencyform2)
          )
        })
        this.selectProps = []
      }
      this.is_title = i
      this.dialogVisible = true
      if (this.$refs.addcurrencyform) {
        this.$refs.addcurrencyform.resetFields()
      }
    },
    addCurrency() {
      if (!this.selectProps.length) {
        return this.$message.warning('请选择属性')
      }
      if (this.is_title === 1) {
        this.addSection()
      } else {
        this.upSection()
      }
    },
    setpaginationOptions(opt) {
      for (const key in opt) {
        this.paginationOptions[key] = opt[key]
      }
      this.getList()
    },
    // 查询
    getList() {
      const { pageSize, currentPage } = this.paginationOptions
      axios
        .get('baseProperty/list_page', {
          params: {
            pageSize,
            currentPage,
            ...this.searchForm
          },
          baseURL: '/api/manage/rest'
        })
        .then((res) => {
          if (res.code === 200) {
            this.userData = res.data.records
            this.paginationOptions.total = res.data.total
          } else {
            this.$alert(res.message, '错误提示', {
              dangerouslyUseHTMLString: true
            })
          }
        })
    },
    // 部门职员查询
    selectSection() {
      const url = `baseProperty/get?id=${this.formId}`
      axios.get(url).then((res) => {
        if (res.code === 200) {
          const data = res.data
          for (const item in data) {
            if (data[item] && !Array.isArray(data[item])) {
              data[item] = data[item] + ''
            }
          }
          this.addcurrencyform = Object.assign({}, data)
          this.is_title = 2
          this.dialogVisible = true
        } else {
          this.$alert(res.message, '错误提示', {
            dangerouslyUseHTMLString: true
          })
        }
      })
    },
    // 修改
    upSection() {
      const url = 'baseProperty/update'
      this.$refs.addcurrencyform.validate((valid) => {
        if (valid) {
          const propertyValueIds = []
          this.selectProps.forEach((item) => {
            item.children.forEach((ee) => {
              propertyValueIds.push(ee.id)
            })
          })
          axios
            .post(url, { ...this.addcurrencyform, propertyValueIds })
            .then((res) => {
              // eslint-disable-next-line eqeqeq
              if (res.code == 200) {
                this.dialogVisible = false
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.getList(this.currentPage)
              } else {
                this.$alert(res.message, '错误提示', {
                  dangerouslyUseHTMLString: true
                })
              }
            })
        }
      })
    },
    // 新增
    addSection() {
      const url = 'baseProperty/add'
      this.$refs.addcurrencyform.validate((valid) => {
        if (valid) {
          const propertyValueIds = []
          this.selectProps.forEach((item) => {
            item.children.forEach((ee) => {
              propertyValueIds.push(ee.id)
            })
          })
          axios
            .post(url, {
              ...this.addcurrencyform,
              propertyValueIds: propertyValueIds
            })
            .then((res) => {
              if (res.code === 200) {
                this.dialogVisible = false
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.getList(this.currentPage)
              } else {
                this.$alert(res.message, '错误提示', {
                  dangerouslyUseHTMLString: true
                })
              }
            })
        }
      })
    },
    // 删除
    deleteSection(v) {
      let arr = []
      if (v) arr.push(v)
      else arr = this.selection
      const leng = arr.length
      if (leng === 0) {
        return this.$message('请勾选至少一条记录')
      }
      let ids = []
      ids = arr.map((v) => {
        return v.id
      })
      ids = ids.join()
      this.$confirm('确定删除选中的信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const url = `baseProperty/delete?ids=${ids}`
          axios.get(url).then((res) => {
            // eslint-disable-next-line eqeqeq
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList(this.currentPage)
            } else {
              this.$alert(res.message, '错误提示', {
                dangerouslyUseHTMLString: true
              })
            }
          })
        })
        .catch(() => {})
    }
  }
}
</script>
<style lang="scss" scoped>
.wrap {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table_wrap {
  background: #fff;
  flex: 1;
  overflow: hidden;
}

.prop-checkbox {
  margin-top: 10px;
  &::v-deep {
    .el-checkbox__label {
      font-size: 12px;
      width: 85px;
      overflow: hidden;
      white-space: nowrap;
      vertical-align: middle;
      text-overflow: ellipsis;
    }

    .el-checkbox {
      padding: 3px;
      padding-bottom: 3px;
      min-width: 110px;
      border: 1px solid #dcdfe6;
      box-sizing: border-box;
      border-radius: 4px;
      padding-left: 5px;
      padding-right: 5px;
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}
.prop-label {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.variants + .variants {
  border-top: 1px solid #bbb;
}

.title {
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  line-height: 36px;
  padding-left: 10px;
  border-bottom: 1px solid #efefef;
  margin-bottom: 10px;
}

.variants li {
  display: inline-block;
  position: relative;
  width: 100px;
  padding: 0 6px;
  margin-left: 6px;
  box-sizing: border-box;
  border: 1px solid #dcdfe6;
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
  white-space: nowrap;

  font-weight: 500;
  font-size: 12px;
  line-height: 24px;
  color: #606266;
  cursor: pointer;
  text-overflow: ellipsis;
  padding-right: 10px;
}

.variants li i {
  position: absolute;
  top: 7px;
  right: 5px;
}
</style>

<style>
.customsize-label .el-select-dropdown__list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  overflow: hidden auto;
  width: 500px;
  gap: 6px;
  padding-left: 6px;
}

.customsize-label.el-select-dropdown.is-multiple
  .el-select-dropdown__item.selected::after {
  content: '';
  display: none;
}

.customsize-label .el-select-dropdown__item.selected .el-tag {
  background-color: #ecf5ff;
  display: inline-block;
  font-size: 12px;
  color: #409eff;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
}

.customsize-label .el-select-dropdown__item {
  padding: 0px;
  white-space: nowrap;
  flex-shrink: 0;
  padding-right: 0 !important;
}

.custom-dialog .el-dialog__body {
  height: 600px;
}
</style>
