<template>
  <div class="wrap card">
    <el-form :inline="true" size="mini">
      <el-form-item label style="margin-bottom: 0px">
        <ul class="calcul-tat-bar" style="width: 200px">
          <li class="my-flex tabt-bar-nav">
            <span
              class="my-flex-1"
              :class="{ active: is_tab == '1' }"
              @click="handleClick('1')">
              类别
            </span>
            <span
              class="my-flex-1"
              :class="{ active: is_tab == '2' }"
              @click="handleClick('2')">
              风格
            </span>
          </li>
        </ul>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px">
        <el-button type="success" @click="addDialog(1)">新增</el-button>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px">
        <el-button type="danger" @click="deleteSection()">删除</el-button>
      </el-form-item>
      <el-form-item style="margin-bottom: 0px">
        <el-button type="warning" @click="getList(1)">刷新</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="my-table-cont my-flex-1">
      <table-view
        ref="multipleTable"
        :sourceData="sourceData"
        :treeConfig="{ children: 'children' }"
        :selection="true"
        @selectionChange="(v) => (selections = v)"
        :tableColumns="tableColumns"></table-view>
    </div>
    <div class="pagination" v-if="is_tab == 2">
      <el-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
      :close-on-click-modal="false"
      :title="is_title == 1 ? '新增' : '编辑'"
      :visible.sync="dialogVisible"
      width="640px">
      <el-form
        label-position="right"
        label-width="100px"
        size="mini"
        :inline="true"
        :model="addcurrencyform"
        :rules="addrules"
        ref="addcurrencyform">
        <el-form-item label="上级分类" v-if="is_tab == '1'" prop="pid">
          <!-- <el-select v-model="addcurrencyform.pid" placeholder="请选择上级分类">
            <el-option v-for="item in all_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>-->
          <el-cascader
            clearable
            style="width: 164px"
            v-model="addcurrencyform.pid"
            :options="all_list"
            :props="pidoptions"
            :show-all-levels="false"></el-cascader>
        </el-form-item>
        <el-form-item
          label="类别中文名"
          prop="name"
          v-if="is_tab == '1'"
          required>
          <el-input
            v-model="addcurrencyform.name"
            placeholder="请输入类别中文名称"></el-input>
        </el-form-item>
        <el-form-item
          label="类别英文名"
          prop="enname"
          v-if="is_tab == '1'"
          required>
          <el-input
            v-model="addcurrencyform.enname"
            placeholder="请输入类别英文名称"></el-input>
        </el-form-item>
        <el-form-item
          label="风格名称"
          prop="name"
          v-if="is_tab == '2'"
          required>
          <el-input
            v-model="addcurrencyform.name"
            placeholder="请输入类别名称"></el-input>
        </el-form-item>
        <el-form-item
          label="风格编码"
          prop="code"
          v-if="is_tab == '2'"
          required>
          <el-input
            v-model="addcurrencyform.code"
            placeholder="请输入类别名称"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="remark">
          <el-input
            style="width: 164px"
            v-model="addcurrencyform.sort"
            placeholder="排序"></el-input>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input
            style="width: 438px"
            v-model="addcurrencyform.remark"
            placeholder="请输入备注信息"></el-input>
        </el-form-item>
        <el-form-item label="相关风格" prop="styleIds" v-if="is_tab == '1'">
          <el-select
            v-model="addcurrencyform.styleIds"
            multiple
            placeholder="请选择相关风格"
            style="width: 438px"
            filterable>
            <el-option
              v-for="(item, index) in all_list2"
              :key="index"
              :label="item.name"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="SKU属性"
          prop="skuPropertyIds"
          required
          v-if="
            is_tab == '1' && (addcurrencyform.pid === 0 || !addcurrencyform.pid)
          ">
          <el-select
            v-model="addcurrencyform.skuPropertyIds"
            multiple
            filterable
            placeholder="请选择相关属性"
            style="width: 438px">
            <el-option
              v-for="item in skuCategory"
              :key="item.id"
              :value="item.id"
              :label="item.cnname + '(' + item.enname + ')'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="一般属性"
          prop="generalPropertyIds"
          v-if="
            is_tab == '1' && (addcurrencyform.pid === 0 || !addcurrencyform.pid)
          ">
          <el-select
            v-model="addcurrencyform.generalPropertyIds"
            multiple
            filterable
            placeholder="请选择相关属性"
            style="width: 438px">
            <el-option
              v-for="item in generalCategory"
              :key="item.id"
              :value="item.id"
              :label="item.cnname + '(' + item.enname + ')'"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="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
      :title="`设置默认供应商(${currentCateName})`"
      :visible.sync="setDefVisivle"
      width="790px"
      :close-on-click-modal="false">
      <el-input
        v-model="supplierName"
        placeholder=""
        style="width: 200px; margin-bottom: 10px"
        clearable></el-input>

      <div style="min-height: 100px; max-height: 500px">
        <el-radio-group v-model="supplierId" style="width: 100%">
          <div
            style="display: inline-block; width: 33.33%; margin-bottom: 10px"
            v-for="(item, index) in supplierlist"
            :key="index">
            <el-radio :label="item.id">{{ item.name }}</el-radio>
          </div>
        </el-radio-group>
      </div>
      <span slot="footer">
        <el-button @click="setDefVisivle = false">取消</el-button>
        <el-button type="primary" @click="submitDefaultSupplier">
          保存
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from '../../common/api/axios'
import TableView from '@/common/components/base/tableView.vue'

export default {
  name: 'supply_category',
  components: {
    TableView
  },
  data() {
    return {
      currentCateName: '',
      select_tab: 'LB',
      istab: 'LB',

      is_title: 1,
      sourceData: [],
      dialogVisible: false,
      addcurrencyform: {
        code: '',
        id: '',
        name: '',
        enname: '',
        shopId: '',
        type: '',
        styleIds: [],
        styleNames: '',
        pid: 0,
        propertyIds: []
      },
      addcurrencyform2: null,
      formId: null,
      addrules: {},
      all_list: [],
      all_list2: [],
      is_tab: '1',
      pidoptions: {
        label: 'name',
        value: 'id',
        checkStrictly: true,
        emitPath: false
      },
      paginationOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      category: [],
      supplierList: [],
      currentCateId: '',
      setDefVisivle: false,
      supplierId: '',
      supplierName: '',
      selections: [],
      skuCategory: [],
      generalCategory: []
    }
  },
  created() {
    // this.alllist("baseStyleInfo/all_list", "all_list2");
    this.getList(1)
    this.addcurrencyform2 = JSON.parse(JSON.stringify(this.addcurrencyform))
  },
  computed: {
    supplierlist() {
      return this.supplierList.filter(
        (item) => item.name && item.name.indexOf(this.supplierName) !== -1
      )
    },
    tableColumns() {
      let arr = []
      if (this.is_tab === '1') {
        arr = [
          {
            label: '类别中文名',
            key: 'name',
            width: 200,
            align: 'left',
            treeNode: true,
            render: (item) => (
              <div>
                <span
                  class={
                    item.deep === 1
                      ? 'el-icon-folder'
                      : item.deep === 2
                      ? 'el-icon-folder-opened'
                      : 'el-icon-tickets'
                  }
                  style={{
                    color:
                      item.deep === 1
                        ? '#4168FF'
                        : item.deep === 2
                        ? '#67c23a'
                        : ''
                  }}></span>
                <span>{item.name}</span>
              </div>
            )
          },
          {
            label: '类别英文名',
            key: 'enname',
            align: 'left',
            width: 130
          },
          {
            label: '相关风格',
            key: 'styleNames',
            align: 'left',
            width: 200
          },
          {
            label: 'SKU属性',
            key: 'skuPropertyNames',
            align: 'left',
            width: 200
          },
          {
            label: '一般属性',
            key: 'propertyNames',
            align: 'left'
          }
        ]
      } else {
        arr = [
          {
            label: '风格名称',
            key: 'name',
            align: 'left'
          },
          {
            label: '风格编码',
            key: 'code',
            align: 'left'
          }
        ]
      }
      return [
        ...arr,
        {
          label: '排序',
          key: 'sort',
          align: 'right',
          width: 100
        },
        {
          label: '备注信息',
          key: 'remark',
          align: 'center'
        },
        {
          label: '相关操作',
          key: '',
          align: 'center',
          fixed: 'right',
          width: 100,
          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>
          )
        }
      ]
    }
  },
  // watch: {
  //   select_tab(val) {
  //     if (this.istab == val) return;
  //     this.istab = val;
  //     this.currentPage = 1;
  //     this.getList(1);
  //   }
  // },
  filters: {
    text_join(value) {
      if (!value) return ''
      return value.join(',')
    }
  },

  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(
          this.is_tab === '1'
            ? 'baseCategoryInfo/importBaseCategoryInfo'
            : 'baseStyleInfo/importBaseStyleInfo',
          form
        )
        console.log(res)
        if (res.code === 200) {
          this.$message.success('导入成功')
          this.getList()
        }
      }
    },
    onCurrentChange(currentPage) {
      this.paginationOptions.currentPage = currentPage
      this.getList()
    },
    sizeChange(pageSize) {
      this.paginationOptions.pageSize = pageSize
      this.getList()
    },
    submitDefaultSupplier() {
      axios
        .post('baseCategoryInfo/setDefaultSupplier', {
          id: this.currentCateId,
          defaultSupplierId: this.supplierId
        })
        .then((res) => {
          this.$message.success(res.message)
          this.setDefVisivle = false
          this.getList()
        })
        .catch((err) => console.log(err))
    },
    setDefSupplier(item) {
      this.currentCateId = item.id
      this.currentCateName = item.name
      this.supplierId = ''
      axios
        .get('supplySupplier/getSupplyByCategory', {
          params: { categoryId: item.id }
        })
        .then((res) => {
          const supplierList = res.data || []
          if (supplierList.length === 0) {
            return this.$message.warning('该分类下暂无供应商')
          } else {
            this.setDefVisivle = true
            this.supplierList = supplierList
          }
        })
    },
    getStyle() {
      if (this.all_list2.length > 0) return
      this.alllist('baseStyleInfo/all_list', 'all_list2')
      if (this.skuCategory.length > 0) return
      this.alllist('baseProperty/all_list_sku', 'skuCategory')
      if (this.generalCategory.length > 0) return
      this.alllist('baseProperty/all_list_general', 'generalCategory')
    },
    search() {
      this.currentPage = 1
      this.getList(1)
    },
    handleClick(v) {
      this.is_tab = v
      this.selections = []
      this.getList(1)
    },
    currentTabFn(val) {
      if (val) this.formId = val.id
      else this.formId = null
    },
    addDialog(i, v = null) {
      this.getStyle()
      if (this.is_tab === '1') {
        this.alllist('baseCategoryInfo/tree_list', 'all_list')
      }
      if (i === 2) {
        if (v) this.formId = v.id
        if (!this.formId) {
          return this.$message('请勾选至少一条记录')
        }
        this.selectSection()
      } else {
        this.$nextTick(() => {
          this.addcurrencyform = JSON.parse(
            JSON.stringify(this.addcurrencyform2)
          )
        })
        this.is_title = i
        this.dialogVisible = true
      }
      if (this.$refs.addcurrencyform) {
        this.$refs.addcurrencyform.resetFields()
      }
    },
    addCurrency() {
      this.$refs.addcurrencyform.validate((valid) => {
        if (valid) {
          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() {
      if (this.is_tab === '2') {
        const { pageSize, currentPage } = this.paginationOptions
        axios
          .get('baseStyleInfo/list_page', {
            params: {
              pageSize: pageSize,
              currentPage: currentPage
            },
            baseURL: '/api/manage/rest'
          })
          .then((res) => {
            if (res.code === 200) {
              this.formId = null
              this.sourceData = res.data.records

              this.paginationOptions.total = res.data.total
            } else {
              this.$alert(res.message, '错误提示', {
                dangerouslyUseHTMLString: true
              })
            }
          })
      } else {
        this.alllist('baseCategoryInfo/tree_list', 'sourceData')
      }
    },
    selectSection() {
      const text = this.is_tab === '1' ? 'baseCategoryInfo' : 'baseStyleInfo'
      const url = `${text}/get?id=${this.formId}`
      axios
        .get(url, {
          baseURL: '/api/manage/rest'
        })
        .then((res) => {
          if (res.code === 200) {
            const data = res.data
            this.addcurrencyform = Object.assign({}, data)
            this.is_title = 2
            this.dialogVisible = true
          } else {
            this.$alert(res.message, '错误提示', {
              dangerouslyUseHTMLString: true
            })
          }
        })
    },
    upSection() {
      const text = this.is_tab === '1' ? 'baseCategoryInfo' : 'baseStyleInfo'
      const url = `${text}/update`
      axios.post(url, this.addcurrencyform).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
          })
        }
      })
    },
    addSection() {
      const text = this.is_tab === '1' ? 'baseCategoryInfo' : 'baseStyleInfo'
      const url = `${text}/add`
      axios.post(url, this.addcurrencyform).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.selections
      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 text =
            this.is_tab === '1' ? 'baseCategoryInfo' : 'baseStyleInfo'
          const url = `${text}/delete?ids=${ids}`
          axios.get(url).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getList(this.currentPage)
            }
          })
        })
        .catch(() => {})
    },
    alllist(url, arr) {
      axios.get(url, { baseURL: '/api/manage/rest' }).then((res) => {
        if (res.code === 200) {
          this[arr] = res.data
          this.$nextTick(() => {
            if (this.$refs.addcurrencyform) {
              this.$refs.addcurrencyform.clearValidate()
            }
          })
        } else {
          this.$alert(res.message, '错误提示', {
            dangerouslyUseHTMLString: true
          })
        }
      })
    }
  }
}
</script>
<style>
.wrap {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-wrap {
  background: #fff;
  flex: 1;
  overflow: hidden;
}
</style>
