<template>
  <a-form
    :model="form"
    ref="formRef"
    label-align="left"
    :label-col="{ span: 6 }"
    :wrapper-col="{ span: 18 }"
  >
    <a-row>
      <a-col :span="24">
        <a-form-item
          label="品牌商名称"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 21 }"
          name="orgName"
          required
          :rules="[{ required: true, message: '请输入品牌商名称' }]"
        >
          <a-input v-model:value="form.orgName" placeholder="请输入品牌商名称" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="24">
        <a-form-item
          label="品牌商编码"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 21 }"
          name="orgName"
          required
          :rules="[{ required: true, message: '请输入品牌商编码' }]"
        >
          <a-input v-model:value="form.orgCode" placeholder="请输入品牌商编码" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="24">
        <a-card size="small">
          <template #title>
            <span>已授权区域</span>
            <a-cascader
              :options="zoneOptions"
              :load-data="loadZoneData"
              placeholder="请选择行政区划"
              @change="addOrgZone"
            >
              <a-button type="primary" size="small" style="margin-left: 15px;">
                授权
              </a-button>
            </a-cascader>
          </template>
          <!-- 表格 -->
          <a-table
            :pagination="false"
            :columns="columns"
            :dataSource="dataSource"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a @click="removeOrgZone(record)">移除</a>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </a-form>
</template>

<script setup>
import { ref } from 'vue'
import { callUser, callOperate } from '@/apis/call.js'
import { message } from 'ant-design-vue'
import { dataFormat } from '@/utils/tools'
import { getCache } from '@/utils/authority';

const formRef = ref();
const formData = () => ({
  orgId: "",
  orgName: "",
  createdTime: ""
});
const form = ref(formData());

// 表格行数据
const dataSource = ref([])
const data = ref([])
// 表格列配置
const columns = ref([
  {
    title: '序号',
    key: 'index',
    width: 70,
    align: 'center',
    dataIndex: 'index'
  },
  {
    key: 'zoneName',
    title: '区域名称',
    dataIndex: 'zoneName',
    align: 'center'
  },
  {
    key: 'assignedTime',
    title: '授权时间',
    align: 'center',
    dataIndex: 'assignedTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 320,
    align: 'center'
  }
])

const zoneOptions = ref([])

const openForm = (params = {}) => {
  form.value = {
    ...formData()
  }
  if (params['orgId']) {
    callUser("/organizations/getInfo/"+ params['orgId'], {}, "get").then(res => {
      if (res.code == 200) {
        if (res.data) {
          form.value = {
            ...res.data
          };
        }
      } else {
        message.error(res.message);
      }
    });
    getOrgZoneList(params['orgId']);
  }
  loadFristZoneData();
};

/**
 * 加载区域数据
 */
const loadFristZoneData = () => {
  zoneOptions.value = [];
  callOperate("/ebikeOperateSystem/ebikeAdministrationZone", {}, "get").then(res => {
    if (res.code == 200) {
      let opt = []
      res.data.map(item => {
        opt.push({ label: item['name'], value: item['id'], isLeaf: item['isLeaf'] })
      })
      zoneOptions.value = opt;
    }
  })
}

const loadZoneData = (data) => {
  if (data) {
    let pindex = 0;
    let parentId = data[0].value;
    if (data.length > 0) {
      pindex = data.length - 1;
      parentId = data[pindex].value; 
    }
    callOperate("/ebikeOperateSystem/ebikeAdministrationZone?parent_id=" + parentId, {}, "get").then(res => {
      if (res.code == 200) {
        let opt = []
        res.data.map(item => {
          opt.push({ label: item['name'], value: item['id'], isLeaf: item['isLeaf'] })
        })
        setZoneData(zoneOptions.value,'value', parentId,'children',opt);
      }
    })
  }
}

const setZoneData = (arr,keyname,keyvalue,name,value) => {
  arr.map(item => {
    if (item[keyname] == keyvalue) {
      item[name] = value;
    }
    if (item['children']) {
      setZoneData(item['children'],keyname,keyvalue,name,value)
    }
  })
}

const getOrgZoneList = (orgId) => {
  callOperate("/ebikeOrgZone/list?orgId=" + orgId, {}, "get").then((res) => {
    if (res.code!= 200) {
        message.error(res.message)
        return
    }
    if (res.data) {
      data.value = res.data
      data.value = data.value.map((item, index) => {
        index++
        return { ...item, index }
      })
      dataSource.value = data.value
    } 
  }) 
}

const removeOrgZone = (record) => {
  callOperate("/ebikeOrgZone/remove?id=" + record.id, { }, "post").then((res) => {
    if (res.code!= 200) {
        message.error(res.message)
        return
    }
    getOrgZoneList(form.value.orgId); 
  })
}

const addOrgZone = (data) => {
  let zoneId = "";
  if (data.length > 0) {
    zoneId = data[data.length - 1];
  } else {
    zoneId = "";
  }
  if (!zoneId) {
    message.error('请选择行政区划') 
  }
  const userinfo = getCache('ebike-userinfo');
  const params = {
    orgId: form.value.orgId, 
    zoneId: zoneId,
    staffId: userinfo.username,
    assignedTime: dataFormat(new Date(),'yyyy-MM-dd HH:mm:ss')
  }
  callOperate("/ebikeOrgZone/save", params, "post").then((res) => {
    if (res.code!= 200) {
        message.error(res.message)
        return
    }
    getOrgZoneList(form.value.orgId);
    loadFristZoneData(); 
  })
}

const formSave = (callBack) => {
  formRef.value.validate().then(() => {
    let params = {
      orgId: "",
      orgName: "",
      orgCode: "",
      createdTime: dataFormat(new Date(),'yyyy-MM-dd HH:mm:ss'),
    }
    if (form.value.orgId) {
      params = {
        ...form.value
      }
      callUser("/organizations/update", params).then(res => {
          if (res.code != 200) {
            message.error(res.message);
            if (callBack) {
              callBack(false, res);
            }
            return;
          }
          if (callBack) {
            callBack(true, res);
          }
          resetAll();
      }).catch(error => {
        if (callBack) {
            callBack(false, error);
          }
      });
    }
    else {
      callUser("/organizations/save", params).then(res => {
        if (res.code!= 200) {
          message.error(res.message);
          if (callBack) {
            callBack(false, res);
          }
          return;
        }
        if (callBack) {
          callBack(true, res);
        }
        resetAll(); 
      }).catch(error => {
        if (callBack) {
          callBack(false, error);
        }
      }); 
    }
  });  
};

const resetAll = (callBack) => {
  Object.assign(form.value, formData());
  data.value = [];
  dataSource.value = [];
  formRef.value.resetFields();
  if (callBack) {
    callBack(true, form.value);
  }
}

defineExpose({ openForm, formSave, resetAll });
</script>
