<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item :label="$t('grouping.zmc')" prop="title">
        <el-input v-model.trim="form.title" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="省" prop="path">
        <el-cascader
          ref="cascaderItem"
          v-model="areaData"
          placeholder="请选择"
          :options="cityData"
          :props="optionProps"
        ></el-cascader>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { doEdit, doAdd } from '@/api/project';
import { getCity } from '@/api/city';
export default {
  name: 'GroupEdit',
  data() {
    return {
      form: {
        id: '',
        title: '',
        name: '',
        provinceCode: '',
        provinceName: '',
        cityCode: '',
        cityName: '',
        areaCode: '',
        areaName: '',
      },
      optionProps: {
        value: 'areaCode',
        label: 'areaName',
        children: 'children',
      },
      areaData: [],
      cityData: [],
      rules: {
        title: [{ required: true, trigger: 'blur', message: '请输入项目名称' }],
        areaData: [{ required: true, trigger: 'blur', message: '请选择城市' }],
      },
      clearable: true,
      menuId: '',
      parentData: [],
      title: '',
      dialogFormVisible: false,
      diffData: {},
      ruleForm: [],
    };
  },
  created() {
    this.getCityData();
  },
  methods: {
    async getCityData() {
      const { data } = await getCity();
      this.cityData = this.getTreeData(data);
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children 若为空数组，则将 children 设为undefined
          data[i].children = undefined;
        } else {
          // children 若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    handleCountryChange(value) {
      if (value) {
        const len = value.length - 1;
        this.form.parentId = value[len];
      } else {
        this.form.parentId = 0;
      }
    },
    showEdit(row) {
      if (!row) {
        this.title = '添加';
      } else {
        this.title = '编辑';
        this.menuId = row.id;
        this.ruleForm = Object.assign({}, row);
        this.form = Object.assign({}, row);
        this.areaData = [row.provinceCode, row.cityCode, row.areaCode];
        this.form.title = row.name;
      }
      this.dialogFormVisible = true;
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    getDiffData() {
      this.diffData = {};
      Object.keys(this.form).forEach(item => {
        if (this.form[item] != this.ruleForm[item]) {
          this.diffData[item] = this.form[item];
        }
      });
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.form.name = this.form.title;
          const areaData = this.areaData;
          const expenseItem = this.$refs['cascaderItem'].inputValue;
          const name = expenseItem.split(' / ');
          this.form.provinceCode = areaData[0] == undefined ? '' : areaData[0];
          this.form.cityCode = areaData[1] == undefined ? '' : areaData[1];
          this.form.areaCode = areaData[2] == undefined ? '' : areaData[2];
          this.form.provinceName = name[0] == undefined ? '' : name[0];
          this.form.cityName = name[1] == undefined ? '' : name[1];
          this.form.areaName = name[2] == undefined ? '' : name[2];
          if (this.form.id) {
            this.getDiffData();
            if (Object.keys(this.diffData).length != 0) {
              this.diffData.id = this.form.id;
              const { msg } = await doEdit(this.diffData);
              this.$notify({
                title: msg,
                type: 'success',
              });
            }
          } else {
            const { msg } = await doAdd(this.form);
            this.$notify({
              title: msg,
              type: 'success',
            });
          }
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false;
          this.$parent.fetchData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style>
.select {
  width: 100%;
}
</style>
