<template>
  <template-page
    ref="pageRef"
    :getList="getList"
    :operation="operation()"
    :optionsEvensGroup="optionsEvensGroup"
    :columnParsing="columnParsing"
    :tableAttributes="tableAttributes"
    :tableEvents="tableEvents"
    :moreParameters="moreParameters"
  >
    <div class="cartographer_big">
      <el-dialog title="服务产品配置" width="100%" :modal="false" :visible.sync="formBool" :before-close="handleClose">
        <zj-page-container v-if="formBool">
          <zj-page-fill class="neibuview">
            <zj-form-container ref="formRef" :form-data="formData" :form-attributes="{ size: 'mini' }">
              <zj-form-module title="基本信息" label-width="120px" :form-data="formData" :form-items="formItems" />
            </zj-form-container>
            <el-card style="margin-top: 10px" size="mini">
              <div slot="header">
                <el-radio-group v-model="radio1" size="mini">
                  <el-radio-button label="管理后台">管理后台</el-radio-button>
                  <el-radio-button label="小程序">小程序</el-radio-button>
                </el-radio-group>
              </div>
              <zj-tree
                size="mini"
                v-show="radio1 == '管理后台'"
                :data="menus"
                :default-expand-all="true"
                :props="defaultProps"
                show-checkbox
                node-key="moduleId"
                ref="tree"
                highlight-current
              >
              </zj-tree>
              <zj-tree
                size="mini"
                v-show="radio1 == '小程序'"
                :data="minimenus"
                :default-expand-all="true"
                :props="defaultProps"
                show-checkbox
                node-key="moduleId"
                ref="tree22"
                highlight-current
              >
              </zj-tree>
            </el-card>
          </zj-page-fill>
          <div>
            <div style="box-sizing: border-box; padding: 10px; text-align: right">
              <el-button size="mini" @click="handleClose">取 消</el-button>
              <el-button size="mini" @click="formConfirm" type="primary">确 定</el-button>
            </div>
          </div>
        </zj-page-container>
      </el-dialog>
    </div>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import operation_mixin from '@/components/template/operation_mixin.js'
import {
  serviceProductList,
  serviceProductAdd,
  serviceProductUpdate,
  serviceProductDelf
} from '@/api/serviceProductConfig.js'
import { getDataDictionary } from '@/api/dataDictionary.js'
import { required } from '@/components/template/rules_verify.js'
import { getMenuList } from '@/api/setting'
import { getMenuList as getMenuList22 } from '@/api/miniMenus'
import { mapGetters } from 'vuex'
export default {
  components: {
    TemplatePage
  },
  mixins: [operation_mixin],
  data() {
    return {
      // 表单弹窗
      formBool: false,
      formData: {
        dictCode: '',
        dictType: '',
        dictValue: '',
        items: [],
        price: 0,
        remark: '',
        status: true
      },
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      recordSelected: [],
      SERVICE_LABEL: [],
      defaultProps: {
        children: 'children',
        label: 'moduleName'
      },
      radio1: '管理后台',
      minimenus: [],
      menus: []
    }
  },
  computed: {
    ...mapGetters(['userid']),
    moreParameters() {
      return []
    },
    // 用户信息
    userInfo() {
      return JSON.parse(localStorage.getItem('greemall_user'))
    },
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.baseDataList()
                this.formBool = true
              }
            })
          ]
        ]
      ]
    },
    formItems() {
      return [
        {
          name: 'el-select',
          md: 8,
          options: this.SERVICE_LABEL,
          attributes: {
            placeholder: '请选择',
            clearable: true,
            filterable: true
          },
          formItemAttributes: {
            label: '产品服务',
            prop: 'dictCode',
            rules: [...required]
          }
        },
        {
          name: 'el-input',
          md: 8,
          attributes: {},
          formItemAttributes: {
            label: '销售价格（元）',
            prop: 'price',
            rules: [...required]
          }
        },
        {
          md: 8,
          name: 'el-radio',
          options: [
            { label: '开启', value: true },
            { label: '禁用', value: false }
          ],
          attributes: {},
          formItemAttributes: {
            label: '状态',
            prop: 'status',
            rules: [...required]
          }
        }
      ]
    }
  },

  methods: {
    // 列表请求函数
    getList: serviceProductList,

    // 列表导出函数
    // exportList: ,

    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },

    columnParsing(item, defaultData) {
      return defaultData
    },

    operation() {
      return this.operationBtn({
        edit: {
          click: ({ row, index, column }) => {
            this.baseDataList(() => {
              this.formBool = true
              serviceProductDelf({ id: row.id }).then(res => {
                var { items, ...p } = res.data
                this.$refs.tree.setCheckedKeys(
                  items.filter(item => item.isWith === false && item.type === 'PC').map(item => item.moduleId)
                )
                this.$refs.tree22.setCheckedKeys(
                  items.filter(item => item.isWith === false && item.type === 'WX').map(item => item.moduleId)
                )
                this.formData = { ...p }
              })
            })
          }
        }
      })
    },

    getchanpfw() {
      getDataDictionary({
        pageNum: 1,
        pageSize: -1,
        params: [
          { param: 'a.status', compare: '=', value: 'ON' },
          { param: 'a.dict_type', compare: '=', value: 'SERVICE_LABEL' }
        ]
      }).then(res => {
        this.SERVICE_LABEL = res.data.records.map(item => ({
          value: item.dictCode,
          label: item.dictValue
        }))
      })
    },

    handleClose(cb) {
      this.formBool = false
      this.$data.formData = this.$options.data().formData
      this.$refs?.pageRef?.refreshList()
    },

    formConfirm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          ;(this.formData.id ? serviceProductUpdate : serviceProductAdd)({
            ...this.formData,
            items: [
              ...Array.from(new Set([...this.$refs.tree.getCheckedKeys()])).map(id => {
                return { moduleId: id, type: 'PC', isWith: false }
              }),
              ...Array.from(new Set([...this.$refs.tree.getHalfCheckedKeys()])).map(id => {
                return { moduleId: id, type: 'PC', isWith: true }
              }),
              ...Array.from(new Set([...this.$refs.tree22.getCheckedKeys()])).map(id => {
                return { moduleId: id, type: 'WX', isWith: false }
              }),
              ...Array.from(new Set([...this.$refs.tree22.getHalfCheckedKeys()])).map(id => {
                return { moduleId: id, type: 'WX', isWith: true }
              })
            ]
          }).then(res => {
            this.handleClose()
            this.$successMsg('配置成功')
          })
        }
      })
    },

    baseDataList(cb) {
      this.getchanpfw()
      // getCheckedKeys
      Promise.all([getMenuList({ adminUserId: this.userid }), getMenuList22({ adminUserId: this.userid })]).then(
        ([res, res2]) => {
          this.aaa(res.data)
          this.menus = res.data
          this.aaa(res2.data)
          this.minimenus = res2.data
          this.$nextTick(() => {
            cb?.()
          })
        }
      )
    },

    aaa(list) {
      for (var item of list) {
        if (item.type == 3) {
          item.tiling = true
          item.labelWidthNum = 115
        }
        if (item.children && item.children.length) {
          this.aaa(item.children)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.neibuview {
  box-sizing: border-box;
  padding-left: 16px;

  ::v-deep & > .zj-page-fill-scroll {
    box-sizing: border-box;
    padding-right: 16px;

    & > div:nth-child(1) {
      margin-top: 20px;
    }
  }
}
</style>
