<template>
  <div class="add-block">
    <ai-detail>
      <template #title>
        <ai-title
            :title="pageTitle"
            :isShowBack="true"
            :isShowBottomBorder="true"
            @onBackClick="cancel(false)"
        />
      </template>
      <template #content>
        <el-form ref="rules" :model="forms" :rules="formRules" size="small" label-suffix="：" label-width="120px">
          <ai-card title="基础信息">
            <template slot="content">
              <el-form-item label="网格名称" prop="girdName">
                <el-input v-model="forms.girdName" placeholder="请输入…" :maxlength="50" show-word-limit clearable/>
              </el-form-item>
              <el-form-item label="网格长" prop="girdMemberManageList">
                <ai-user-selecter isShowUser :instance="instance" v-model="forms.girdMemberManageList" :props="{label:'name', id: 'id'}"/>
              </el-form-item>
              <el-form-item label="网格员" prop="girdMemberList">
                <ai-user-selecter isShowUser :instance="instance" v-model="forms.girdMemberList" :props="{label:'name', id: 'id'}"/>
              </el-form-item>
            </template>
          </ai-card>
          <ai-card title="其他信息">
            <template slot="content">
              <el-row type="flex">
                <div class="fill">
                  <el-form-item label="初始日期" prop="startDate">
                    <el-date-picker
                        v-model="forms.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期"
                        style="width: 100%;"/>
                  </el-form-item>
                  <el-form-item label="终止日期" prop="endDate">
                    <el-date-picker v-model="forms.endDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" style="width: 100%;"/>
                  </el-form-item>
                </div>
                <div class="fill">
                  <el-form-item label="面积" prop="area">
                    <el-input v-model="forms.area" placeholder="面积㎡" clearable/>
                  </el-form-item>
                </div>
              </el-row>
              <el-form-item label="网格地址" prop="address">
                <el-input v-model="forms.address" placeholder="限200字" maxlength="200"></el-input>
              </el-form-item>
              <el-form-item label="网格范围" prop="enclosure">
                <map-plotting v-model="forms.points">
                  <el-button size="small">地图标绘</el-button>
                </map-plotting>
              </el-form-item>
            </template>
          </ai-card>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="cancel(false)" class="delete-btn footer-btn">
          取 消
        </el-button>
        <el-button type="primary" @click="save()" class="footer-btn">
          提 交
        </el-button>
      </template>
    </ai-detail>
  </div>
</template>

<script>
import {mapState} from "vuex";
import MapPlotting from "./mapPlotting";
import AiUserPicker from "../../components/AiUserPicker";

export default {
  name: "addBlock",
  components: {AiUserPicker, MapPlotting},
  props: {
    instance: Function,
    dict: Object,
    params: Object,
  },
  data() {
    return {
      forms: {
        girdMemberManageList: [],
        girdMemberList: []
      },
      options: [],
      parentGirdInfo: {},
    };
  },
  computed: {
    ...mapState(["user"]),
    formRules() {
      return {
        girdName: [
          {required: true, message: "请输入网格名称", trigger: "change"},
        ],
        girdCode: [
          {required: true, message: "请输入网格编号"},
          {pattern: /^\d+$/g, message: "请输入数字"},
        ]
      };
    },
    unitProps() {
      return {
        value: "id",
        checkStrictly: true,
        emitPath: false,
      };
    },
    unitOps() {
      let initData = JSON.parse(JSON.stringify(this.options)),
          ops = initData.filter((e) => !e.parentId);
      ops.map((e) => this.addChild(e, initData));
      return ops;
    },
    pageTitle() {
      return this.isEdit ? "编辑网格区块" : "添加网格区块"
    },
    isEdit() {
      return !!this.$route.query.id;
    }
  },
  created() {
    if (this.isEdit) {
      this.searchDetail();
    } else {
      this.forms = {
        ...this.forms,
        ...this.$route.query
      }
    }
  },
  methods: {
    cancel() {
      this.$router.push({})
    },
    // 获取所有单位
    getAllUnit(data) {
      this.options = [];
      this.instance.post("/admin/sysunit/getAll", null, {
        params: {areaId: data},
      }).then((res) => {
        if (res?.data) {
          res.data = res.data.map((a) => {
            return {...a, label: a.name}
          });
          this.options = res.data.filter((e) => !e.parentId);
          this.options.map((t) => this.addChild(t, res.data));
        }
      });
    },
    save() {
      this.$refs["rules"].validate((valid) => {
        if (valid) {
          let {girdMemberManageList, girdMemberList} = this.forms
          this.instance.post(`/app/appgirdinfo/addOrUpdate`, {
            ...this.forms,
            girdMemberManageList: girdMemberManageList?.map(v => ({wxUserId: v.id})) || [],
            girdMemberList: girdMemberList?.map(v => ({wxUserId: v.id})) || []
          }).then((res) => {
            if (res.code == 0) {
              this.cancel(true)
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    searchDetail() {
      let {id} = this.$route.query
      this.instance.post(`/app/appgirdinfo/queryDetailById`, null, {
        params: {id},
      }).then((res) => {
        if (res?.data) {
          this.forms = {
            ...res.data,
            girdMemberManageList: res.data.girdMemberManageList ? res.data.girdMemberManageList.map(v => {
              return {
                ...v,
                id: v.wxUserId,
                avatar: v.photo
              }
            }) : [],
            girdMemberList: res.data.girdMemberList ? res.data.girdMemberList.map(v => {
              return {
                ...v,
                id: v.wxUserId,
                avatar: v.photo
              }
            }) : []
          };
          this.parentGirdInfo = res.data.parentGirdInfo;
          this.forms.parentGirdName = res.data.parentGirdInfo && res.data.parentGirdInfo.girdName;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.add-block {
  width: 100%;
  height: 100%;

  .footer-btn {
    width: 92px;
  }
}
</style>
