<template>
  <el-dialog v-dialogDrag :title="isEdit ? $t('orderAuthor.modifyPermissions') : $t('orderAuthor.createPermission')" :visible.sync="dialogShow" width="420px" :before-close="handleClose">
    <div>
      <el-form ref="form" label-position="right" :model="editModel" label-width="80px" :rules="editRules" size="mini" @submit.native.prevent>
        <el-form-item :label="$t('orderAuthor.permissionName')" prop="name">
          <el-input v-model="editModel.name" />
        </el-form-item>
        <el-form-item :label="$t('orderAuthor.describtion')">
          <el-input v-model="editModel.des" />
        </el-form-item>
        <el-form-item :label="$t('orderAuthor.permissionType')" prop="permissionType">
          <el-select v-model="editModel.permissionType" :placeholder="$t('map.pleaseSelect')">
            <el-option
              v-for="item in permissionTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editModel.permissionType === 0" label="项目" prop="projectCode">
          <el-select v-model="editModel.projectCode" :placeholder="$t('map.pleaseSelect')">
            <el-option
              v-for="item in projectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editModel.permissionType === 1 || editModel.permissionType === 2" label="线路" prop="mapId">
          <el-select v-model="editModel.mapId" :placeholder="$t('map.pleaseSelect')" @change="mapIdChange">
            <el-option
              v-for="item in mapList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editModel.permissionType === 2" :label="$t('orderAuthor.ability')" prop="abilityIds">
          <el-select v-model="editModel.abilityIds" multiple :placeholder="$t('map.pleaseSelect')">
            <el-option
              v-for="item in filterAbilityList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogShow = false">{{ $t('map.cancel') }}</el-button>
      <el-button type="primary" :loading="loading" @click="saveAs">{{ $t('map.confirm') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { createPermission, updatePermission } from '@/api/permissionManage';

export default {
    name: 'MapSaveAs',
    props: {
        abilityList: {
            required:true,
            type:Array
        },
        mapList: {
            required:true,
            type:Array
        },
        projectList: {
            required:true,
            type:Array
        }
    },
    data() {
        return {
            dialogShow: false,
            loading: false,
            isEdit: false,
            editModel: {
                name: '',
                des: '',
                permissionType: '',
                projectCode: '',
                mapId: '',
                abilityIds: []
            },
            editRules: {
                name: [
                    { required: true, message: this.$t('rules.enterPermissionName'), trigger: 'blur' }
                ],
                permissionType: [
                    { required: true, message: '请选择权限类型!', trigger: 'blur' }
                ],
                projectCode: [
                    { required: true, message: '请选择项目!', trigger: 'blur' }
                ],
                mapId: [
                    { required: true, message: '请选择线路!', trigger: 'blur' }
                ],
                abilityIds: [
                    { required: true, message: '请选择功能!', trigger: 'blur' },
                    { validator: this.validateLimit, trigger: 'blur' }
                ]
            }
        };
    },
    computed: {
        mapName() {
            let name = '';
            const findObj = this.mapList.find(item => {
                return item.value == this.editModel.mapId;
            });
            if (findObj && this.editModel.mapId) {
                name = findObj.label;
            }
            return name;
        },
        filterAbilityList() {
            return this.abilityList.filter(item => {
                return item.mapName == this.mapName;
            });
        },
        permissionTypeList() {
            return this.$ConstSelect.permissionTypeList;
        }
    },
    methods: {
        mapIdChange() {
            this.editModel.abilityIds = [];
        },
        validateLimit(rule, value, callback) {
            const num = value.length;
            if (num >= 1) {
                callback();
            } else {
                callback(new Error('请选择功能!'));
            }
        },
        doShow(data) {
            if (data) {
                this.isEdit = true;
                const abilityIds = [];
                data.abilityVOList && data.abilityVOList.forEach(item => {
                    abilityIds.push(item.id);
                });
                this.editModel = {
                    ...data,
                    mapId: data.mapId ? String(data.mapId) : '',
                    abilityIds: abilityIds
                };
            } else {
                this.isEdit = false;
                this.initData();
            }
            this.dialogShow = true;
        },
        initData() {
            this.editModel = {
                name: '',
                des: '',
                permissionType: '',
                projectCode: '',
                mapId: '',
                abilityIds: []
            };
        },
        close() {
            this.initData();
            this.dialogShow = false;
        },
        handleClose() {
            this.close();
        },
        saveAs() {
            this.$refs['form'].validate((valid) => {
                if (!valid) { return; }
                this.loading = true;
                let apiFn = createPermission;
                if (this.isEdit) {
                    apiFn = updatePermission;
                }
                const cpData = Object.assign({}, this.editModel);
                if (this.editModel.permissionType === 0) {
                    delete cpData.mapId;
                    cpData.abilityIds = [];
                } else if (this.editModel.permissionType === 1) {
                    delete cpData.projectCode;
                    cpData.abilityIds = [];
                } else if (this.editModel.permissionType === 2) {
                    delete cpData.projectCode;
                }
                apiFn(cpData).then((res) => {
                    this.loading = false;
                    this.$message.success(`${this.isEdit ? '编辑' : '新建'}成功！`);
                    this.$emit('refresh');
                    this.close();
                }).catch((err) => {
                    console.log('err', err);
                    this.loading = false;
                    this.$message.error(`${this.isEdit ? '编辑' : '新建'}失败！，${err.message}`);
                });
            });
        }
    }
};
</script>
