<template>
  <div class="app-container">
    <card-table :modalData="areaList" labelWidth="120px" :searchParams="queryParams" @pagination="getList"
      :loading="loading" :tableSearch="true" @columnSearch="handleQuery" :delProp="['createTime']"
      @resetList="resetQuery" @selection-change="handleSelectionChange" show-no show-selection
    >
      <template #operations="{ selections }">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['user:area:add']">
            {{ $t('area.addArea') }}</el-button>
        </el-col>
        <el-col :span="1.5" style="margin-left: 10px;">
          <el-button plain icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['user:area:export']">{{ $t('common.export') }}</el-button>
        </el-col>
      </template>
      <template #default="{ list }">
        <!--<el-table-column type="selection" width="50" align="center"/>-->
        <!--<el-table-column label="No." type="index" width="50" align="center" />-->
        <Column :label="$t('area.areaName')" prop="areaName" :searchParams="queryParams" :showSearch="true"
          width="250px" />
        <Column :label="$t('area.areaNameUS')" prop="areaNameUS" :searchParams="queryParams" :showSearch="true"
          width="250px" />
        <Column :label="$t('area.areaNameRU')" prop="areaNameRU" :searchParams="queryParams" :showSearch="true"
          width="250px" />
        <Column :label="$t('area.areaNameES')" prop="areaNameES" :searchParams="queryParams" :showSearch="true"
          width="250px" />
        <Column :label="$t('area.areaLevel')" prop="areaLevel" :searchParams="queryParams" :showSearch="true"
          width="200px" searchType="select" :searchDict="dict.type.area_level" select-more>
          <template #default="{ row }">
            <span>{{ row.areaLevelName }}</span>
          </template>
        </Column>
        <Column :label="$t('area.parentArea')" prop="parentArea" :searchParams="queryParams" :showSearch="true"
          searchType="select" :searchDict="allAreaList" select-more width="250px">
          <template #default="{ row }">
            <span>{{ row.parentAreaName }}</span>
          </template>
        </Column>
        <Column :label="$t('personal.createDate')" prop="createTime" width="300px" :searchParams="queryParams"
          :showSearch="true" searchType="dateRange">
          <template #default="{ row }">
            <span>{{ parseTime(row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </Column>
        <Column :label="$t('common.remark')" prop="remark" width="300px" />
        <Column :label="$t('common.operate')" :min-width="250" fixed="right" :showSearch="true" searchType="operate">
          <template #default="{ row }">
            <el-button v-if="row.areaLevel != 0" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)"
              v-hasPermi="['user:area:edit']">{{ $t('common.edit') }}</el-button>
            <el-button v-if="row.areaLevel != 0" size="mini" type="text" icon="el-icon-delete"
              @click="handleDelete(row)" v-hasPermi="['user:area:remove']">{{ $t('common.delete') }}</el-button>
          </template>
        </Column>
      </template>
    </card-table>

    <!-- 添加或修改区域对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" :before-close="cancel" append-to-body>
      <el-form class="area-form" ref="form" :model="form" :rules="rules" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('area.areaName')" prop="areaName">
              <el-input style="width: 100%;" v-model.trim="form.areaName" maxlength="100"
                :placeholder="$t('common.pleaseInput') + $t('area.areaName')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('area.areaNameUS')" prop="areaNameUS">
              <el-input style="width: 100%;" v-model.trim="form.areaNameUS" maxlength="100"
                :placeholder="$t('common.pleaseInput') + $t('area.areaNameUS')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('area.areaNameRU')" prop="areaNameRU">
              <el-input style="width: 100%;" v-model.trim="form.areaNameRU" maxlength="100"
                :placeholder="$t('common.pleaseInput') + $t('area.areaNameRU')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('area.areaNameES')" prop="areaNameES">
              <el-input style="width: 100%;" v-model.trim="form.areaNameES" maxlength="100"
                :placeholder="$t('common.pleaseInput') + $t('area.areaNameES')" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('area.areaLevel')" prop="areaLevel">
              <el-select style="width: 100%;" v-model="form.areaLevel" @change="areaLevelChange"
                :placeholder="$t('common.pleaseSelect') + $t('area.areaLevel')" clearable>
                <el-option v-for="dict in dict.type.area_level" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('area.parentArea')" prop="parentArea">
              <el-select style="width: 100%;" v-model="form.parentArea" :disabled="form.areaLevel == '1'"
                @change="parentAreaChange" :placeholder="$t('common.pleaseSelect') + $t('area.parentArea')" clearable>
                <el-option v-for="item in levelAreaList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item :label="$t('area.containNation')" prop="countryIds">
            <el-transfer class="transfer-box" ref="myTransfer" v-model="form.countryIds" :data="nationList" filterable
              :filter-placeholder="$t('common.pleaseInput')"></el-transfer>
          </el-form-item>
        </el-row>
        <el-form-item :label="$t('common.remark')" prop="remark">
          <el-input style="width: 100%;" v-model="form.remark" type="textarea"
            :placeholder="$t('common.pleaseInput') + $t('common.remark')" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-circle-check" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArea, getArea, addArea, updateArea, delArea, getAllAreaList } from "@/api/user/area";
import { getAllNationList } from "@/api/user/country";
import { getCountryByAreaId } from "@/api/system/user";
import { parseTime } from "../../../utils/ruoyi";
import Column from "../../../components/element/table/Column.vue";

export default {
  name: "Area",
  components: { Column },
  dicts: ['area_level'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 区域表格数据
      areaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaLevel: ''
      },
      // 所有国家列表
      nationList: [],
      // 所有区域列表
      allAreaList: [],
      levelAreaList: [],
      language: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        areaName: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('area.areaName'), trigger: "blur" },
          // { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: this.$t('common.noSpace'), trigger: 'blur' }
        ],
        areaNameRU: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('area.areaNameRU'), trigger: "blur" },
          // { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: this.$t('common.noSpace'), trigger: 'blur' }
        ],
        areaNameUS: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('area.areaNameUS'), trigger: "blur" },
          // { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: this.$t('common.noSpace'), trigger: 'blur' }
        ],
        areaNameES: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('area.areaNameES'), trigger: "blur" },
          // { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: this.$t('common.noSpace'), trigger: 'blur' }
        ],
        areaLevel: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('area.areaLevel'), trigger: "change" }
        ],
        parentArea: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('area.parentArea'), trigger: "change" }
        ],
        countryIds: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('area.containNation'), trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.language = this.$i18n.locale;
    this.getAreaList();
    this.getList(this.queryParams);
  },
  methods: {
    parseTime,
    /** 查询区域列表 */
    getList(param) {
      this.loading = true;
      listArea(param).then(response => {
        this.areaList = response.rows;
        this.queryParams.total = response.total;
        this.areaList.forEach(item => {
          item.areaLevelName = this.dict.label.area_level[item.areaLevel];
        });
        this.loading = false;
      });
    },
    /** 获取所有区域列表 */
    getAreaList() {
      getAllAreaList().then(response => {
        this.allAreaList = response.data.map(item => {
          let label = '';
          switch (this.language) {
            case 'chinese':
              label = item.areaName
              break;
            case 'english':
              label = item.areaNameUS
              break;
            case 'russia':
              label = item.areaNameRU
              break;
            case 'spanish':
              label = item.areaNameES
              break;
          }
          return {
            value: item.areaId,
            label: label,
            level: item.areaLevel
          };
        });
      })
    },
    formatCountry(list) {
      return list.map(item => {
        let label = '';
        switch (this.language) {
          case 'chinese':
            label = item.countryName
            break;
          case 'english':
            label = item.countryNameUS
            break;
          case 'russia':
            label = item.countryNameRU
            break;
          case 'spanish':
            label = item.countryNameES
            break;
        }
        return {
          key: item.countryId,
          label: label
        }
      })
    },
    /** 获取所有国家列表 */
    getNationList() {
      getAllNationList().then(response => {
        this.nationList = this.formatCountry(response.data)
      })
    },
    // 区域等级变化
    areaLevelChange() {
      if (this.form.areaLevel == '1') {
        this.levelAreaList = this.allAreaList
        this.$set(this.form, 'parentArea', 0)
        this.getNationList()
      } else {
        this.$set(this.form, 'parentArea', '')
        this.nationList = []
        this.levelAreaList = this.allAreaList.filter(item => item.level == Number(this.form.areaLevel) - 1);
      }
    },
    // 上级区域变化
    parentAreaChange() {
      if (this.form.parentArea) {
        this.$set(this.form, 'countryIds', [])
        // 查询上级区域拥有的国家
        this.getCountryByAreaId();
      }
    },
    getCountryByAreaId() {
      getCountryByAreaId(this.form.parentArea).then(response => {
        this.nationList = this.formatCountry(response.data)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.myTransfer.$refs.leftPanel.checked = []
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery(param) {
      param.pageNum = 1;
      this.getList(param);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        areaLevel: ''
      }
      this.getList(this.queryParams);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.areaId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.levelAreaList = []
      this.nationList = []
      this.$nextTick(() => {
        this.reset();
      })
      this.form.areaLevel = '';
      this.form.parentArea = '';
      this.open = true;
      this.title = this.$t('area.addArea');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getArea(row.areaId).then(response => {
        this.form = response.data;
        if (this.form.parentArea == 0) {
          this.getNationList();
        } else {
          this.getCountryByAreaId();
        }
        this.levelAreaList = this.allAreaList.filter(item => item.level == Number(this.form.areaLevel) - 1);
        if (response.data.countryIds) {
          this.form.countryIds = response.data.countryIds.split(',').map(item => Number(item))
        } else {
          this.form.countryIds = []
        }
        this.open = true;
        this.title = this.$t('area.editArea');
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理国家id
          let form = Object.assign({}, this.form)
          if (form.countryIds && form.countryIds.length > 0) {
            form.countryIds = this.form.countryIds.join(',')
          } else {
            form.countryIds = null
          }
          if (form.areaId != undefined) {
            updateArea(form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess(this.$t('common.editSuccess'));
                this.open = false;
                this.getList(this.queryParams);
              } else {
                this.$modal.msgError(response.msg);
              }
            }).catch(() => { });
          } else {
            addArea(form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess(this.$t('common.addSuccess'));
                this.open = false;
                this.getList(this.queryParams);
              } else {
                this.$modal.msgError(response.msg);
              }
            }).catch(() => { });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const areaIds = row.areaId;
      this.$modal.confirm(this.$t('common.isDelete')).then(function () {
        return delArea(areaIds);
      }).then(() => {
        this.getList(this.queryParams);
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.language = this.$i18n.locale;
      // this.queryParams.ids = this.ids;
      let fileName = this.$t('common.areaManage') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      this.download('user/area/export', { ...this.queryParams, ids: this.ids }, fileName)
    }
  }
};
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .el-transfer-panel__header {
  display: none;
}

.area-form {
  padding: 0 20px;
}

::v-deep .area-form .el-form-item--medium .el-form-item__label {
  line-height: 10px;
}

::v-deep .transfer-box .el-input {
  width: auto;
}

::v-deep .transfer-box .el-transfer-panel {
  width: 240px;
}
</style>
