<template>
  <el-dialog
    fullscreen
    :title="title"
    :visible.sync="dialogFormVisible"
    @close="close"
  >
    <el-form
      ref="form"
      :inline="true"
      label-width="100px"
      :model="form"
      :rules="rules"
      size="medium"
    >
      <el-form-item
        :label="__('类型名称')"
        label-width="100px"
        prop="type_name"
        :style="{ width: '30%' }"
      >
        <el-input
          v-model="form.type_name"
          clearable
          :placeholder="__('请输入类型名称')"
          :style="{ width: '100%' }"
        />
      </el-form-item>
      <el-form-item
        :label="__('选择关联规格')"
        label-width="100px"
        prop="type_spec_ids"
        :style="{ width: '30%' }"
      >
        <el-input
          v-model="type_spec_names"
          clearable
          :placeholder="__('请输入选择关联规格')"
          readonly
          :style="{ width: '100%' }"
          @click.native="handleClick"
        />
      </el-form-item>
      <el-form-item
        :label="__('选择关联品牌')"
        label-width="100px"
        prop="type_brand_ids"
        :style="{ width: '30%' }"
      >
        <el-input
          v-model="type_brand_names"
          clearable
          :placeholder="__('请输入选择关联品牌')"
          readonly
          :style="{ width: '100%' }"
          @click.native="brandHandleClick"
        />
      </el-form-item>
      <el-form-item
        :label="__('选择分类')"
        label-width="100px"
        prop="type_category_id"
        :style="{ width: '30%' }"
      >
        <tree-select
          ref="treeSelect"
          :checked-keys="defaultCheckedKeys"
          clearable
          :data="data"
          :default-props="defaultProps"
          :height="300"
          :node-key="nodeKey"
          size="small"
          :width="220"
          @change="change"
        />
      </el-form-item>
      <el-form-item
        :label="__('是否草稿')"
        label-width="100px"
        prop="type_is_draft"
        :style="{ width: '30%' }"
      >
        <el-radio-group v-model="form.type_is_draft" size="medium">
          <el-radio
            v-for="(item, index) in type_is_draftOptions"
            :key="index"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div>
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button type="primary" @click="save">{{ __('确定') }}</el-button>
    </div>

    <el-divider />

    <el-row>
      <el-col :span="15">
        <el-button
          :disabled="form.type_id ? false : true"
          type="primary"
          @click="addAssist"
        >
          {{ __('新增记录') }}
        </el-button>
        <el-button
          :disabled="form.type_id ? false : true"
          type="primary"
          @click="doEdits"
        >
          {{ __('保存') }}
        </el-button>
      </el-col>
      <el-col :span="9">
        <el-button
          :disabled="form.type_id ? false : true"
          type="primary"
          @click="addItem"
        >
          {{ __('新增') }}
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <!-- 第一列栅格布局 -->
      <el-col :span="15">
        <el-table
          ref="itemTable"
          border
          :data="assis"
          height="550"
          highlight-current-row
          :row-class-name="tableRowClassName"
          @row-click="rowClick"
        >
          >
          <el-table-column :label="__('属性名称')" prop="assist_name" />
          <el-table-column :label="__('属性值列')" prop="assist_item" />
          <el-table-column :label="__('是否搜索')" prop="assist_is_search">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.assist_is_search"

                :active-value="1"

                :inactive-value="0"
              />
            </template>
          </el-table-column>
          <el-table-column :label="__('显示类型')" prop="assist_format">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.assist_format"
                :placeholder="__('请输入辅助属性排序')"
              >
                <el-option
                  v-for="item in formatOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :label="__('排序')" prop="assist_order">
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.assist_order"
                :placeholder="__('请输入排序')"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" :label="__('操作')">
            <template slot-scope="scope">
              <!-- 删除 -->
              <el-button
                :plain="true"
                size="mini"
                type="danger"
                @click="delAssist(scope.$index, scope.row.assist_id)"
              >
                {{ __('删除') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <!-- 第二列布局 -->
      <el-col :span="9">
        <el-table ref="itemTable" border :data="itemTable" height="550">
          <el-table-column
            :label="__('辅助属性名称')"
            prop="assist_name"
            width="180"
          >
            <!-- eslint-disable-next-line vue/no-unused-vars -->
            <template slot-scope="scope">
              <el-input
                v-model="assisName"
                :placeholder="__('请输入辅助属性名称')"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="__('辅助属性值名称')"
            prop="assist_item_name"
            width="180"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.assist_item_name"
                :placeholder="__('请输入辅助属性值名称')"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column
            :label="__('辅助属性排序')"
            prop="assist_item_order"
            width="180"
          >
            <template slot-scope="scope">
              <el-input
                v-model.number="scope.row.assist_item_order"
                :placeholder="__('请输入辅助属性排序')"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" :label="__('操作')">
            <template slot-scope="scope">
              <!-- 删除 -->
              <el-button
                :plain="true"
                size="mini"
                type="danger"
                @click="delAssistItem(scope.$index, scope.row.assist_item_id)"
              >
                {{ __('删除') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-dialog
      append-to-body
      :title="__('规格')"
      :visible.sync="specDialogVisible"
    >
      <el-scrollbar style="height: 450px">
        <el-row
          v-for="(s, key, index) in specForm"
          :key="index"
          class="table-layout"
        >
          <el-divider />
          <el-col :span="4">
            {{ key }}
          </el-col>

          <el-col :span="20">
            <el-checkbox-group v-model="selectSpecs">
              <span v-for="spec in s" :key="spec.spec_id" class="spec">
                <el-checkbox :label="spec">
                  {{ spec.spec_name }}
                </el-checkbox>
              </span>
            </el-checkbox-group>
          </el-col>
        </el-row>
        <el-divider />
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirm(false)">{{ __('取消') }}</el-button>
        <el-button type="primary" @click="confirm(true)">
          {{ __('确定') }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      append-to-body
      :title="__('品牌')"
      :visible.sync="brandDialogVisible"
    >
      <el-scrollbar style="height: 450px">
        <el-row
          v-for="(b, key, index) in brandForm"
          :key="index"
          class="table-layout"
        >
          <el-divider />
          <el-col :span="4">
            {{ key }}
          </el-col>

          <el-col :span="20">
            <el-checkbox-group v-model="selectBrands">
              <span v-for="brand in b" :key="brand.brand_id" class="spec">
                <el-checkbox :label="brand">
                  {{ brand.brand_name }}
                </el-checkbox>
              </span>
            </el-checkbox-group>
          </el-col>
        </el-row>
        <el-divider />
      </el-scrollbar>
      <div slot="footer" class="dialog-footer">
        <el-button @click="brandConfirm(false)">{{ __('取消') }}</el-button>
        <el-button type="primary" @click="brandConfirm(true)">
          {{ __('确定') }}
        </el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import {
    doEdit,
    getAssist,
    delAssist,
    delAssistItem,
    doEdits,
  } from '@/api/base/product/type'
  import TreeSelect from '@/components/treeSelect'
  import { getSpecMap } from '@/api/base/product/spec'
  import { getTree } from '@/api/base/product/category'
  import { getBrandMap } from '@/api/base/product/brand'

  export default {
    name: 'BaseProductTypeEdit',
    components: { TreeSelect },
    data() {
      return {
        currentRowIndex: undefined,
        assisName: '',
        itemTable: [],
        assis: [],
        //表格数据
        type_spec_names: '',
        type_brand_names: '',
        selectSpecs: [], // 预选
        selectedSpecs: [], // 已选
        selectBrands: [], // 预选
        selectedBrands: [], // 已选
        specForm: {},
        brandForm: {},
        form: {
          type_name: undefined,
          type_category_id: undefined,
          type_spec_ids: undefined,
          type_is_draft: 1,
          type_brand_ids: undefined,
        },
        rules: {
          type_name: [
            {
              required: true,
              message: this.__('请输入类型名称'),
              trigger: 'blur',
            },
          ],
          /*type_spec_ids: [
            {
              required: true,
              message: this.__('请输入选择关联规格'),
              trigger: 'change',
            },
          ],*/
          /*type_brand_ids: [
            {
              required: true,
              message: this.__('请输入选择关联品牌'),
              trigger: 'change',
            },
          ],*/
          type_is_draft: [
            {
              required: true,
              message: this.__('是否草稿不能为空'),
              trigger: 'change',
            },
          ],
        },
        type_is_draftOptions: [
          {
            label: this.__('草稿'),
            value: 1,
          },
          {
            label: this.__('发布'),
            value: 0,
          },
        ],
        formatOptions: [
          {
            value: 'select',
            label: 'select',
          },
          {
            value: 'checkbox',
            label: 'checkbox',
          },
          {
            value: 'radio',
            label: 'radio',
          },
          // {
          //   value: 'text',
          //   label: 'text',
          // },
        ],
        title: '',
        dialogFormVisible: false,
        specDialogVisible: false,
        brandDialogVisible: false,
        data: [], // 产品规格数据
        defaultCheckedKeys: [],
        nodeKey: 'id',
        defaultProps: {
          children: 'children',
          label: 'label',
        },
      }
    },
    watch: {
      itemTable: {
        deep: true,
        // eslint-disable-next-line no-unused-vars
        handler(val, oldVal) {
          if (typeof this.currentRowIndex !== 'undefined') {
            this.assis[this.currentRowIndex].assist_item = val
              .map((item) => {
                return item.assist_item_name
              })
              .join()
          }
        },
      },
      assisName: {
        // eslint-disable-next-line no-unused-vars
        handler(val, oldVal) {
          if (val && typeof this.currentRowIndex !== 'undefined') {
            this.assis[this.currentRowIndex].assist_name = val
          }
        },
      },
    },
    created() {
      // 初始化分类数据
      this.getTree()
      // 初始化规格参数
      this.getSpecMap()
      // 初始化品牌
      this.getBrandMap()
    },
    methods: {
      async doEdits() {
        const { msg, status } = await doEdits({
          assists: JSON.stringify(this.assis),
        })
        this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
        if (status === 200) {
          this.getAssist(this.form.type_id)
          this.clearAssistItem()
        }
      },
      tableRowClassName({ row, rowIndex }) {
        row.index = rowIndex
      },
      // 辅助属性行点击事件
      // eslint-disable-next-line no-unused-vars
      rowClick(row, column, event) {
        this.itemTable = row.items
        this.assisName = row.assist_name
        this.currentRowIndex = row.index
      },
      // 获取辅助属性数据
      async getAssist(type_id) {
        if (type_id) {
          const { data } = await getAssist({ type_id })
          this.assis = data
        }
      },
      async delAssist(index, assist_ids) {
        this.$baseConfirm(this.__('你确定要删除选中项吗'), null, async () => {
          if (!assist_ids) {
            this.assis.splice(index, 1)
            this.clearAssistItem()
            return
          }
          const { msg, status } = await delAssist({
            assist_ids: String(assist_ids),
          })
          this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
          await this.getAssist(this.form.type_id)
          if (status === 200) this.clearAssistItem()
        })
      },
      async delAssistItem(index, assist_item_ids) {
        this.$baseConfirm(this.__('你确定要删除选中项吗'), null, async () => {
          if (!assist_item_ids) {
            this.itemTable.splice(index, 1)
            return
          }
          const { msg, status } = await delAssistItem({
            assist_item_ids: String(assist_item_ids),
          })
          this.itemTable.splice(index, 1)

          /*await this.getAssist(this.form.type_id)
          this.clearAssistItem()*/
          this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
        })
      },
      clearForm() {
        this.form.type_is_draft = 1
        this.form.type_id = undefined
        this.form.type_name = undefined
        this.form.type_spec_ids = undefined
        this.form.type_brand_ids = undefined
      },
      clearSelected() {
        this.selectSpecs = [] // 预选
        this.selectedSpecs = [] // 已选
        this.selectBrands = [] // 预选
        this.selectedBrands = [] // 已选
        this.type_brand_names = undefined
        this.type_spec_names = undefined
      },
      clearAssistItem() {
        this.currentRowIndex = undefined
        this.itemTable = []
        this.assisName = ''
      },
      // 添加辅助属性事件
      addAssist() {
        this.assisName = ''
        this.itemTable = []
        this.assis.push({
          type_id: this.form.type_id,
          assist_format: 'checkbox',
          assist_is_search: 1,
          assist_item: '',
          assist_name: '',
          assist_order: 0,
          items: [],
        })
        this.currentRowIndex = this.assis.length - 1
        this.assisName = this.assis[this.currentRowIndex].assist_name
      },
      // 添加辅助属性item数据事件
      addItem() {
        if (this.assis.length > 0) {
          this.itemTable = this.assis[this.currentRowIndex].items
          this.itemTable.push({
            assist_item_order: 0,
          })
        } else {
          this.$baseAlert('请先点击右边的“新增记录”，再新增属性！')
        }
      },
      // 规格参数确定事件
      confirm(flag) {
        // 确定
        if (flag) {
          this.selectedSpecs = this.selectSpecs
          this.type_spec_names = this.selectedSpecs
            .map((item) => {
              return item.spec_name
            })
            .join(', ')
          this.form.type_spec_ids = this.selectedSpecs
            .map((item) => {
              return item.spec_id
            })
            .join(',')
        } else {
          // 取消
          this.selectSpecs = this.selectedSpecs
        }

        this.specDialogVisible = false
      },
      // 品牌确定事件
      brandConfirm(flag) {
        // 确定
        if (flag) {
          this.selectedBrands = this.selectBrands
          this.type_brand_names = this.selectedBrands
            .map((item) => {
              return item.brand_name
            })
            .join(', ')
          this.form.type_brand_ids = this.selectedBrands
            .map((item) => {
              return item.brand_id
            })
            .join(',')
        } else {
          // 取消
          this.selectBrands = this.selectedBrands
        }

        this.brandDialogVisible = false
      },
      // 规格参数input 点击事件
      handleClick() {
        this.specDialogVisible = true
      },
      // 品牌input 点击事件
      brandHandleClick() {
        this.brandDialogVisible = true
      },
      // 分类下拉组件数据改变事件
      change(id) {
        this.form.type_category_id = id
      },
      // 获取规格数据
      async getTree() {
        const { data } = await getTree()
        this.data = data
      },
      async getSpecMap() {
        const { data } = await getSpecMap()
        this.specForm = data
      },
      async getBrandMap() {
        const { data } = await getBrandMap()
        this.brandForm = data
      },
      __,
      showEdit(row) {
        if (!row) {
          this.title = this.__('新增')
        } else {
          this.title = this.__('编辑')
          this.form = Object.assign({}, row)
          if (row.type_category_id) {
            this.defaultCheckedKeys.push(row.type_category_id)
          }

          let specIds = row.type_spec_ids.split(',')
          let brandIds = row.type_brand_ids.split(',')
          this.defaultSelected(specIds)
          this.brandDefaultSelected(brandIds)
          this.getAssist(row.type_id)
        }
        this.dialogFormVisible = true
      },
      // 规格参数默认选中
      defaultSelected(specIds) {
        const values = this.flatten(Object.values(this.specForm))
        const selects = values.filter((item) =>
          specIds.includes(item.spec_id.toString())
        )
        this.selectedSpecs = this.selectSpecs = selects
        this.type_spec_names = this.selectedSpecs
          .map((item) => {
            return item.spec_name
          })
          .join(', ')
        this.form.type_spec_ids = this.selectedSpecs
          .map((item) => {
            return item.spec_id
          })
          .join(',')
      },
      // 品牌默认选中
      brandDefaultSelected(brandIds) {
        const values = this.flatten(Object.values(this.brandForm))
        const selects = values.filter((item) =>
          brandIds.includes(item.brand_id.toString())
        )
        this.selectedBrands = this.selectBrands = selects
        this.type_brand_names = this.selectedBrands
          .map((item) => {
            return item.brand_name
          })
          .join(', ')
        this.form.type_brand_ids = this.selectedBrands
          .map((item) => {
            return item.brand_id
          })
          .join(',')
      },
      // 扁平化数组方法
      flatten(arr) {
        return arr.reduce((result, item) => {
          return result.concat(Array.isArray(item) ? this.flatten(item) : item)
        }, [])
      },
      // 弹框关闭
      close() {
        this.$refs['treeSelect'].isShowSelect = false
        this.$refs['treeSelect'].selectedData = []
        this.defaultCheckedKeys = []
        this.$refs['form'].resetFields()
        this.defaultCheckedKeys = []
        this.assis = []
        this.clearAssistItem()
        this.clearSelected()
        this.clearForm()
        this.dialogFormVisible = false
      },
      // 保存类型参数
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const { msg, status, data } = await doEdit(this.form)
            if (data) this.form.type_id = data
            if (200 == status) {
              this.$baseMessage(msg, 'success')
            } else {
              this.$baseMessage(msg, 'error')
            }
            this.$emit('fetch-data')
          } else {
            return false
          }
        })
      },
    },
  }
</script>
<style scoped>
  .el-row {
    margin-bottom: 20px;
  }
  .row-bg {
    padding: 10px 0;
  }
  .spec {
    margin-right: 20px;
  }
</style>
