<template>
  <div>
    <en-table-layout :tableData="tableData.data" :loading="loading">
      <template #toolbar>
        <div class="inner-toolbar w-11/12 flex justify-between">
          <div class="toolbar-btns">
            <el-button size="mini" v-if="checkPermission(['warehouse:add'])" type="primary" @click="handleAddWarehouse">新增</el-button>
          </div>
          <div class="toolbar-search">
            <en-table-search @search="searchEvent" placeholder="请输入关键字搜索" />
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column prop="sn" label="仓库编号" />
        <el-table-column prop="name" label="仓库名称" />
        <el-table-column prop="phone" label="负责人手机号" />
        <el-table-column prop="name" label="仓库地址">
          <template #default="scope">
            {{ adminName(scope.row.ware_pro_city_area) + scope.row.warehouse_address || '' }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="仓库说明" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" v-if="checkPermission(['warehouse:update'])" @click="handleEditWarehouse(scope.$index, scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </template>
      <template #pagination>
        <el-pagination
          v-if="tableData.data && tableData.data.length"
          @size-change="handlePageSizeChange"
          @current-change="handlePageCurrentChange"
          :current-page="tableData.page_no"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="tableData.page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.data_total"
        >
        </el-pagination>
      </template>
    </en-table-layout>

    <el-dialog
      :title="stockForm.id ? '编辑仓库' : '添加仓库'"
      v-model="dialogVisible"
      width="500px"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="stockForm" :rules="stockRules" ref="stockForm" label-width="120px">
        <el-form-item label="仓库编号" prop="sn">
          <el-input v-model="stockForm.sn" :minlength="2" :maxlength="4" clearable placeholder="请输入仓库编号"></el-input>
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="stockForm.name" :minlength="2" :maxlength="20" clearable placeholder="请输入仓库名称"></el-input>
        </el-form-item>
        <el-form-item label="发货人姓名">
          <el-input v-model="stockForm.user_name" :minlength="2" :maxlength="20" clearable placeholder="请输入发货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="发货人电话" prop="phone">
          <el-input v-model="stockForm.phone" :minlength="2" :maxlength="20" clearable placeholder="请输入发货人电话"></el-input>
        </el-form-item>
        <el-form-item label="仓库地址">
          <el-cascader size="large" :options="options" clearable v-model="selectedOptions"> </el-cascader>
          <span>
            <el-input style="margin-top: 10px" v-model="stockForm.warehouse_address" placeholder="请输入"></el-input>
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="stockForm.description" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitWarehouseForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex';
import { ElMessageBox } from 'element-plus';
import * as API_BasicSetting from '@/api/basicSetting';
import * as API_Setting from '@/api/setting';
import * as API_Auth from '@/api/auth';
import Storage from '@/utils/storage';
import router from '@/router';
import EnTableLayout from '@/components/TableLayout/index.vue';
import EnTableSearch from '@/components/TableSearch/index.vue';
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';

const store = useStore();
const tableData = ref<any>({});
const loading = ref(false);
const dialogVisible = ref(false);
const stockForm = ref<any>({
  sn: '',
  name: '',
  user_name: '',
  phone: '',
  warehouse_address: '',
  description: '',
  ware_pro_city_area: []
});
const stockRules = ref<any>({
  sn: [{ required: true, message: '请输入仓库编号', trigger: 'blur' }],
  name: [{ required: true, message: '请选择输入仓库名称', trigger: 'blur' }],
  phone: [
    // { required: true, message: '请输入手机号码！', trigger: 'blur' },
    // { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }, options: regionData,
  ],
});
const selectedOptions = ref<any[]>([]);
const options = ref<any[]>(regionData);
const marketingList = ref<any[]>([]);

const params = ref({
  data: [],
  page_no: 1,
  page_size: 10,
  keyword: '',
});

const checkPermission = (permissions: string[]): boolean => {
  // Implement your permission check logic here
  return true;
};

const handleAddWarehouse = () => {
  stockForm.value = {
    dept_id: 0,
    admin_id: store.getters.user.uid,
  };
  dialogVisible.value = true;
};

const handleEditWarehouse = (index: number, row: any) => {
  stockForm.value = { ...row };
  selectedOptions.value = row.ware_pro_city_area;
  dialogVisible.value = true;
};

const searchEvent = (keyword: string) => {
  params.value = {
    ...params.value,
    keyword: keyword,
  };
  params.value.page_no = 1;
  GET_WarehouseList();
};

const handlePageSizeChange = (size: number) => {
  params.value.page_size = size;
  GET_WarehouseList();
};

const handlePageCurrentChange = (page: number) => {
  params.value.page_no = page;
  GET_WarehouseList();
};

const handleDialogOpen = () => {
  setTimeout(() => {
    stockForm.value.clearValidate();
  });
};

const submitWarehouseForm = () => {
  stockForm.value.validate((valid: boolean) => {
    if (valid) {
      const { id } = stockForm.value;
      const params = { ...stockForm.value };
      if (!params.real_name) delete params.real_name;
      params.role_id === '超级仓库' ? (params.role_id = 0) : null;
      delete params.admin_name;
      params.admin_id = JSON.parse(JSON.parse(localStorage.getItem('admin_user')!).data).uid;
      params.ware_pro_city_area = selectedOptions.value.join(',');

      if (id) {
        API_BasicSetting.editWarehouse(id, params).then(() => {
          dialogVisible.value = false;
          store.dispatch('showMessage', { message: '修改成功！', type: 'success' });
          GET_WarehouseList();
        });
      } else {
        API_BasicSetting.addWarehouse(params).then(() => {
          dialogVisible.value = false;
          store.dispatch('showMessage', { message: '添加成功！', type: 'success' });
          GET_WarehouseList();
        });
      }
    } else {
      store.dispatch('showMessage', { message: '表单填写有误，请核对！', type: 'error' });
      return false;
    }
  });
};

const GET_WarehouseList = () => {
  loading.value = true;
  API_BasicSetting.warehouse(params.value)
    .then((response) => {
      loading.value = false;
      response.data.map((el: any) => {
        if (el.ware_pro_city_area !== undefined) {
          el.ware_pro_city_area = el.ware_pro_city_area.split(',');
        }
        return el;
      });
      tableData.value = response;
      console.log(tableData.value);
    })
    .catch(() => {
      loading.value = false;
    });
};

const GET_MarketingList = () => {
  API_BasicSetting.getUserByDept().then((res) => {
    marketingList.value = res;
  });
};

const adminName = (val: string[]) => {
  let text = '';
  if (val !== undefined) {
    text += codeToText[val[0]];
    text += codeToText[val[1]];
    text += codeToText[val[2]];
  }
  return text;
};

onMounted(() => {
  GET_WarehouseList();
  GET_MarketingList();
});
</script>