<template>
  <el-dialog :visible.sync="visible" width="800px" title="用户配置" @open="onOpen">
    <el-form ref="form" :model="form" :rules="rules" label-width="5em" v-loading="loading">
      <el-row v-if="showCurrent">
        <form-col :span="span" label="当前用户" label-width="5em">
          {{form.userName}}
        </form-col>
      </el-row>
      <el-row>
        <group-title title="其他设置"/>
        <form-col :span="8" label="是否为设备管理员" label-width="9em" prop="deviceAdmin">
          <el-switch v-model="form.deviceAdmin" active-text="是" inactive-text="否" @change="onChangeDeviceAdmin"/>
        </form-col>
        <form-col :span="8" label="服务费率" label-width="9em" prop="serviceFeeProportion">
          <el-input-number v-model="form.serviceFeeProportion" :min="0" :max="100" :step="0.1" placeholder="请输入服务费率">
            <template #append>%</template>
          </el-input-number>
        </form-col>
        <form-col :span="8" label="分红比例" label-width="9em" prop="dividendProportion">
          <el-input-number v-model="form.dividendProportion" :min="0" :max="100" :step="0.1" placeholder="请输入分红比例">
            <template #append>%</template>
          </el-input-number>
        </form-col>
      </el-row>

      <!-- 添加基础配置 -->
      <el-row>
        <group-title title="基础配置"/>
        <form-col :span="8" label="取消时长设置" label-width="9em" prop="agoCancel">
          <el-input-number v-model="form.agoCancel" :min="0" placeholder="请输入取消时长">
            <template #append>分钟</template>
          </el-input-number>
        </form-col>
        <form-col :span="8" label="违约金" label-width="9em" prop="penalty">
          <el-input-number v-model="form.penalty" :min="0" placeholder="请输入违约金">
            <template #append>元</template>
          </el-input-number>
        </form-col>
        <form-col :span="8" label="提前开门时间" label-width="9em" prop="beforeTime">
          <el-input-number v-model="form.beforeTime" :min="0" placeholder="请输入提前开门时间">
            <template #append>分钟</template>
          </el-input-number>
        </form-col>
      </el-row>

      <!-- 添加保洁设置 -->
      <el-row>
        <group-title title="保洁设置"/>
        <form-col :span="8" label="保洁时长" label-width="9em" prop="cleanDuration">
          <el-input-number v-model="form.cleanDuration" :min="0" placeholder="请输入保洁时长">
            <template #append>分钟</template>
          </el-input-number>
        </form-col>
        <form-col :span="8" label="保洁通知" label-width="9em" prop="cleanNotice">
          <el-select v-model="form.cleanNotice" placeholder="请选择保洁通知">
            <el-option
              v-for="dict in dict.type.ss_clean_notice"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"/>
          </el-select>
        </form-col>
      </el-row>

      <!-- 添加权限配置 -->
      <el-row>
        <group-title title="前端菜单"/>
        <el-tree
          :data="menuTree"
          show-checkbox
          node-key="menuId"
          :default-checked-keys="Array.isArray(form.appMenus) ? form.appMenus : []"
          :props="defaultProps"
          ref="menuTree"
        ></el-tree>
      </el-row>

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

<script>
import LineField from '@/components/LineField/index.vue'
import GroupTitle from '@/components/GroupTitle/index.vue'
import { SmUserType } from '@/utils/constants'
import { getUser, updateUser } from '@/api/user/user';
import { listMenu as listAppMenu } from "@/api/system/appMenu";
import { mapState } from 'vuex';

export default {
  name: "UserConfigDialog",
  components: { GroupTitle, LineField },
  dicts: ['ss_clean_notice'],
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    userId: {
      type: Number,
      default: null,
    },
    showCurrent: {
      type: Boolean,
      default: false,
    }
  },
  computed: {
    ...mapState({
      dict: state => state.dict // 从 Vuex 中获取 dict
    }),
    SmUserType() {
      return SmUserType
    },
    visible: {
      set(val) {
        this.$emit('update:show', val);
      },
      get() {
        return this.show;
      }
    }
  },
  data() {
    return {
      span: 12,
      form: {
        userId: null,
        userName: '',
        phonenumber: '',
        userType: '',
        deviceAdmin: false,
        serviceFeeProportion: 0,
        dividendProportion: 0,
        agoCancel: 0,
        penalty: 0,
        beforeTime: 0,
        cleanDuration: 0,
        cleanNotice: '',
        appMenus: []
      },
      rules: {
        showBillMobilePrice: [
          { required: true, message: '请输入单价', trigger: 'blur' }
        ]
      },
      loading: false,
      submitLoading: false,
      menuTree: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      }
    }
  },
  methods: {
    onOpen() {
      if (this.userId != null) {
        this.loading = true;
        getUser(this.userId).then(response => {
          this.form = { ...this.form, ...response.data };
          if (this.form.userType !== '00') {
            this.form.dividendProportion *= 100;
          }
          this.getMenuTree();
        }).finally(() => {
          this.loading = false;
        })
      } else {
        this.reset();
      }
    },
    getMenuTree() {
      listAppMenu({pageSize:999}).then(response => {
        this.menuTree = this.transformMenuData(response.rows);
      });
    },
    transformMenuData(data) {
      const map = {};
      data.forEach(item => {
        map[item.menuId] = { ...item, children: [] };
      });
      const tree = [];
      data.forEach(item => {
        if (item.parentId === 0) {
          tree.push(map[item.menuId]);
        } else {
          if (map[item.parentId]) {
            map[item.parentId].children.push(map[item.menuId]);
          }
        }
      });
      return tree;
    },
    submitForm() {
      const checkedNodes = this.$refs.menuTree.getCheckedKeys();
      this.form.appMenus = checkedNodes;
      if (this.form.userType !== '00') {
        this.form.dividendProportion = this.form.dividendProportion / 100;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            this.submitLoading = true;
            updateUser(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.visible = false;
              this.$emit('success');
            }).finally(() => {
              this.submitLoading = false;
            })
          }
        }
      });
    },
    cancel() {
      this.visible = false;
      this.reset();
    },
    reset() {
      this.form = {
        userId: this.userId,
      };
      this.resetForm("form");
    },
    onChangeDeviceAdmin(val) {
      if (val) {
        this.$confirm('【高危操作】是否确认设置用户为设备管理员？<br/>用户将可以通过微信小程序注册设备！', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }).then(() => {
          this.form.deviceAdmin = true;
        }).catch((e) => {
          this.form.deviceAdmin = false;
        });
      }
    },
  }
}
</script>
<style scoped>
.el-dialog__footer{
  padding-top: 30px;
}
</style>
