<template>
  <div class="dark:!bg-[#060818] bg-white p-3">
    <!--     <template #toolbar> flex justify-between -->
    <div class="inner-toolbar w-11/12 mb-4">
      <div class="toolbar-btns">
        <el-popover placement="bottom-start" :width="200"  trigger="hover" >
          <ul class="text-sm">
            <li class="cursor-pointer border-b border-gray-300 pb-1" @click="handleAddWarehouse">添加自建仓</li>
            <li class="cursor-pointer pt-1" @click="AddVirtual">添加虚拟仓</li>
          </ul>
          <template #reference>
            <el-button
              size="default"
              v-if="checkPermission(['warehouse:add']) && store.state.user.user.founder !== 1"
              type="primary"
              @click="handleAddWarehouse"
              >{{ $t('add') }}</el-button
            >
          </template>
        </el-popover>
      </div>
      <div class="mt-5">
        <!-- toolbar-search -->
        <en-table-search class="!justify-start" @search="searchEvent" :placeholder="$t('search_placeholde')" />
      </div>
    </div>
    <!--     </template> -->
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane :label="$t('whole')" name="first">
        <en-table-layout :tableData="tableData.data" :toolbar="false" :loading="loading">
          <template #table-columns>
            <el-table-column prop="sn" :label="$t('warechouse_sn')" min-width="120" />
            <el-table-column prop="name" :label="$t('warechouse_name')" min-width="150" />
            <el-table-column prop="phone" :label="$t('warechouse_phone')" min-width="130" />
            <el-table-column prop="" :label="$t('warechouse_address')" min-width="200">
              <template #default="scope">
                {{ adminName(scope.row.ware_pro_city_area) + scope.row.warehouse_address || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="description" :label="$t('warechouse_remark')" min-width="150" />
            <el-table-column :label="$t('operate')" fixed="right" width="300">
              <template #default="scope">
                <el-button
                  size="small"
                  v-if="checkPermission(['warehouse:update']) && store.state.user.user.founder !== 1"
                  @click="handleEditWarehouse(scope.$index, scope.row)"
                  >{{ $t('edit') }}</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-tab-pane>
      <el-tab-pane :label="$t('selfBuilt')" name="second">
        <en-table-layout :tableData="buildOneselfData.data" :toolbar="false" :loading="loading">
          <template #table-columns>
            <el-table-column prop="sn" :label="$t('warechouse_sn')" min-width="120" />
            <el-table-column prop="name" :label="$t('warechouse_name')" min-width="150" />
            <el-table-column prop="phone" :label="$t('warechouse_phone')" min-width="130" />
            <el-table-column prop="" :label="$t('warechouse_address')" min-width="200">
              <template #default="scope">
                {{ adminName(scope.row.ware_pro_city_area) + scope.row.warehouse_address || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="description" :label="$t('warechouse_remark')" min-width="150" />
            <el-table-column :label="$t('operate')" fixed="right" width="300">
              <template #default="scope">
                <el-button
                  size="small"
                  v-if="checkPermission(['warehouse:update']) && store.state.user.user.founder !== 1"
                  @click="handleEditWarehouse(scope.$index, scope.row)"
                  >{{ $t('edit') }}</el-button
                >
              </template>
            </el-table-column>
          </template>
          <template #pagination>
            <el-pagination
              v-if="buildOneselfData.data && buildOneselfData.data.length"
              @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange"
              :current-page="buildOneselfData.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="buildOneselfData.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="buildOneselfData.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </el-tab-pane>
      <el-tab-pane :label="$t('virtualWarehouse')" name="third">
        <en-table-layout :tableData="virtuallyData.data" :toolbar="false" :loading="loading">
          <template #table-columns>
            <el-table-column prop="sn" :label="$t('warechouse_sn')" min-width="120" />
            <el-table-column prop="name" :label="$t('warechouse_name')" min-width="150" />
            <el-table-column prop="phone" :label="$t('warechouse_phone')" min-width="130" />
            <el-table-column prop="" :label="$t('warechouse_address')" min-width="200">
              <template #default="scope">
                {{ adminName(scope.row.ware_pro_city_area) + scope.row.warehouse_address || '' }}
              </template>
            </el-table-column>
            <el-table-column prop="description" :label="$t('warechouse_remark')" min-width="150" />
            <el-table-column :label="$t('operate')" fixed="right" width="300">
              <template #default="scope">
                <el-button
                  size="small"
                  v-if="checkPermission(['warehouse:update']) && store.state.user.user.founder !== 1"
                  @click="handleEditWarehouse(scope.$index, scope.row)"
                  >{{ $t('edit') }}</el-button
                >
              </template>
            </el-table-column>
          </template>
          <template #pagination>
            <el-pagination
              v-if="virtuallyData.data && virtuallyData.data.length"
              @size-change="handlePageSizeChange"
              @current-change="handlePageCurrentChange"
              :current-page="virtuallyData.page_no"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="virtuallyData.page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="virtuallyData.data_total"
            >
            </el-pagination>
          </template>
        </en-table-layout>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      :title="stockForm.id ? $t('edit') : $t('add')"
      v-model="dialogVisible"
      width="600px"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="!rounded-lg"
    >
      <el-form :model="stockForm" :rules="stockRules" ref="stockFormRef" label-width="180px">
        <el-form-item :label="$t('warechouse_sn')" prop="sn">
          <el-input v-model="stockForm.sn" :minlength="2" :maxlength="4" clearable :placeholder="$t('place') + $t('warechouse_sn')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('warechouse_name')" prop="name">
          <el-input v-model="stockForm.name" :minlength="2" :maxlength="20" clearable :placeholder="$t('place') + $t('warechouse_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('warechouse_user_name')">
          <el-input v-model="stockForm.user_name" :minlength="2" :maxlength="20" clearable :placeholder="$t('place') + $t('warechouse_user_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('warechouse_phone')" prop="phone">
          <el-input v-model="stockForm.phone" :minlength="2" :maxlength="20" clearable :placeholder="$t('place') + $t('warechouse_phone')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('warechouse_address')">
          <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="$t('place') + $t('warechouse_address')"></el-input>
          </span>
        </el-form-item>
        <el-form-item :label="$t('warechouse_remark')" prop="description">
          <el-input
            v-model="stockForm.description"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 4 }"
            :placeholder="$t('place') + $t('warechouse_remark')"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="submitWarehouseForm">{{ $t('submit') }}</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加虚拟仓 -->
    <el-dialog
      :title="stockForm.id ? $t('edit') : $t('add')"
      v-model="virtualVisible"
      width="600px"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="!rounded-lg"
    >
      <el-form :model="stockForm" :rules="stockRules" ref="stockFormRef" label-width="180px">
        <el-form-item :label="$t('名称')" prop="sn">
          <el-input v-model="stockForm.sn" :minlength="2" :maxlength="4" clearable :placeholder="$t('place') + $t('warechouse_sn')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('类型结构')" prop="name">
          <el-input v-model="stockForm.name" :minlength="2" :maxlength="20" clearable :placeholder="$t('place') + $t('warechouse_name')"></el-input>
        </el-form-item>
      <!--   <el-form-item :label="$t('warechouse_user_name')">
          <el-input v-model="stockForm.user_name" :minlength="2" :maxlength="20" clearable :placeholder="$t('place') + $t('warechouse_user_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('warechouse_phone')" prop="phone">
          <el-input v-model="stockForm.phone" :minlength="2" :maxlength="20" clearable :placeholder="$t('place') + $t('warechouse_phone')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('warechouse_address')">
          <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="$t('place') + $t('warechouse_address')"></el-input>
          </span>
        </el-form-item>
        <el-form-item :label="$t('warechouse_remark')" prop="description">
          <el-input
            v-model="stockForm.description"
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 4 }"
            :placeholder="$t('place') + $t('warechouse_remark')"
          ></el-input>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('cancel') }}</el-button>
          <el-button type="primary" @click="submitWarehouseForm">{{ $t('submit') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useStore } from 'vuex';
import { ElMessageBox, FormInstance, ElMessage, TabsPaneContext } 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 { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const activeName = ref('first');

const handleClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.props.name == 'first') {
    GET_WarehouseList();
  } else if (tab.props.name == 'second') {
    GET_buildOneself();
  } else if (tab.props.name == 'third') {
    GET_virtually();
  }
};

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: [],
});
/* console.log(store.state.companId); */
const stockRules = ref<any>({
  sn: [{ required: true, message: t('place') + t('warechouse_sn'), trigger: 'blur' }],
  name: [{ required: true, message: t('place') + t('warechouse_name'), 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<any>({
  data: [],
  page_no: 1,
  page_size: 10,
  keyword: '',
});
const stockFormRef = ref();
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(() => {
    stockFormRef.value.clearValidate();
  });
};

const submitWarehouseForm = () => {
  stockFormRef.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;
          ElMessage.success(t('edit_success'));
          GET_WarehouseList();
        });
      } else {
        API_BasicSetting.addWarehouse(params).then(() => {
          dialogVisible.value = false;
          ElMessage.success(t('add_success'));
          GET_WarehouseList();
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      return false;
    }
  });
};
/* 全部仓 */
const GET_WarehouseList = () => {
  loading.value = true;
  params.value.company_id = store.state.companId;
  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;
    })
    .catch(() => {
      loading.value = false;
    });
};

/* 自建仓 */
const buildOneselfData = ref<any>({});
const GET_buildOneself = () => {
  loading.value = true;
  params.value.company_id = store.state.companId;
  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;
      });
      buildOneselfData.value = response;
    })
    .catch(() => {
      loading.value = false;
    });
};

/* 虚拟仓 */
const virtuallyData = ref<any>({});
const GET_virtually = () => {
  loading.value = true;
  params.value.company_id = store.state.companId;
  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;
      });
      virtuallyData.value = response;
    })
    .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;
};
/* 添加虚拟仓 */
const virtualVisible=ref(false)
const AddVirtual=()=>{
  virtualVisible.value=true
}
onMounted(() => {
  if (activeName.value == 'first') {
    GET_WarehouseList();
  }
  //GET_MarketingList();
});
</script>
<style>
.el-tabs__header {
  margin: 0 0 1px;
}
</style>