<template>
  <div>
    <en-table-layout :tableData="tableData.records" :loading="loading">
      <template #toolbar>
        <div class="inner-toolbar w-11/12 flex justify-between">
          <div class="toolbar-btns">
            <el-button size="small" v-if="checkPermission(['warehouse:add'])" type="primary" @click="handleAddWarehouse">{{$t('add')}}</el-button>
          </div>
          <div class="toolbar-search">
            <en-table-search @search="searchEvent" :placeholder="$t('search_placeholde')" />
          </div>
        </div>
      </template>

      <template #table-columns>
        <el-table-column prop="name" :label="$t('companyName')" width="200" />
        <el-table-column prop="industry" :label="$t('industry')" width="200" />
        <el-table-column prop="user_name" :label="$t('legal_person')" width="200" />
        <el-table-column prop="phone" :label="$t('phone')" width="200" />
        <el-table-column prop="email" :label="$t('companyEmail')" width="200" />
        <el-table-column prop="company_package_id" :label="$t('company_package')" width="200">
          <template #default="scope">
            {{ packageName(scope.row.company_package_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_use_time" :label="$t('end_use_time')" width="200" />
        <el-table-column prop="status" :label="$t('user_state')" width="200">
          <template #default="scope">
            {{ typeName(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('companyAddress')" width="200">
          <template #default="scope">
            {{ adminName(scope.row.province) + scope.row.address }}
          </template>
        </el-table-column>

        <el-table-column :label="$t('operate')" width="300">
          <template #default="scope">
            <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="getBranch('compan', scope.row)">{{$t('view')}}</el-button>
            <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="handleEditWarehouse(scope.$index, scope.row)">{{$t('edit')}}</el-button>
            <el-button size="small" v-if="checkPermission(['warehouse:update'])" @click="handleRenew(scope.$index, scope.row)">{{$t('renew')}}</el-button>
            <el-button size="small" class="mt-1" v-if="scope.row.status !== 1" @click="handleBranch(scope.$index, scope.row)">{{$t('review')}}</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="companyForm.id ? $t('edit') : $t('add')"
      v-model="dialogVisible"
      @open="handleDialogOpen"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="!rounded-lg"
    >
      <el-form :model="companyForm" :rules="stockRules" ref="companyFormRef" label-width="140px">
        <el-row>
          <el-col :span="16">
            <el-form-item :label="$t('companyLicense')+':'" prop="license">
              <el-upload
                :disabled="disabled"
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="companyForm.license" :src="companyForm.license" class="avatar w-28 h-28" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('front_id_card')+':'" prop="id_card_front">
              <el-upload
                :disabled="disabled"
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleFrontSuccess"
                :before-upload="beforeFrontUpload"
              >
                <img v-if="companyForm.id_card_front" :src="companyForm.id_card_front" class="avatar w-28 h-28" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <!--  <p>姓名:{{ companyForm.value.id_card_front.name }}</p>
              <p>身份证号码:{{ companyForm.value.id_card_front.id_card_number }}</p> -->
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('opposite_id_card')+':'" prop="id_card_opposite">
              <el-upload
                :disabled="disabled"
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleOppositeSuccess"
                :before-upload="beforeOppositeUpload"
              >
                <img v-if="companyForm.id_card_opposite" :src="companyForm.id_card_opposite" class="avatar w-28 h-28" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="10" v-if="!companyForm.id">
            <el-form-item :label="$t('company_package')+':'" prop="company_package_id">
              <el-select v-model="companyForm.company_package_id" :disabled="disabled" clearable :placeholder="$t('change')+$t('company_package')">
                <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('companyName')+':'" prop="name">
              <el-input v-model="companyForm.name" clearable disabled :placeholder="$t('company_name')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('credit_code')+':'" prop="credit_code">
              <el-input v-model="companyForm.credit_code" clearable disabled :placeholder="$t('place')+$t('credit_code')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('industry')+':'" prop="industry">
              <el-input v-model="companyForm.industry" :disabled="disabled" clearable :placeholder="$t('place')+$t('industry')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('legal_person')+':'" prop="user_name">
              <el-input v-model="companyForm.user_name" disabled clearable :placeholder="$t('place')+$t('legal_person')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('corporate_phone')+':'" prop="phone">
              <el-input v-model="companyForm.phone" :disabled="disabled" clearable :placeholder="$t('place')+$t('corporate_phone')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('companyEmail')+':'" prop="email">
              <el-input v-model="companyForm.email" :disabled="disabled" clearable :placeholder="$t('place')+$t('companyEmail')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('postalCode')+':'" prop="postal_code">
              <el-input v-model="companyForm.postal_code" :disabled="disabled" clearable :placeholder="$t('place')+$t('postalCode')"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item :label="$t('website')+':'" prop="website">
              <el-input v-model="companyForm.website" :disabled="disabled" clearable :placeholder="$t('place')+$t('website')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item :label="$t('companyAddress')+':'" prop="">
              <el-cascader class="w-full" size="default" :disabled="disabled" :options="options" clearable v-model="selectedOptions"> </el-cascader>
              <span>
                <el-input class="!w-full mt-3" v-model="companyForm.address" :disabled="disabled" :placeholder="$t('place')"></el-input>
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="20" v-if="type == 'examine'">
            <el-form-item :label="$t('reject')+':'" prop="">
              <el-input v-model="companyForm.fail_reason" clearable :placeholder="$t('reject_reason')"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="type !== 'examine'">
          <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="submitWarehouseForm">{{$t('submit')}}</el-button>
        </div>
        <div class="dialog-footer" v-else>
          <el-button @click="submitExamine(2)">{{$t('down')}}</el-button>
          <!-- superUpdateStatus -->
          <el-button type="primary" @click="submitExamine(1)">{{$t('agree_with')}}</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="$t('renew')" v-model="renewVisible" :modal-append-to-body="false" width="450px" :close-on-click-modal="false" :close-on-press-escape="false" class="!rounded-lg">
      <el-form :model="packageForm" :rules="stockRules" ref="packageFormRef" label-width="140px">
        <el-form-item :label="$t('company_package')+':'" prop="company_package_id">
          <el-select v-model="packageForm.company_package_id" clearable :placeholder="$t('change')+$t('company_package')">
            <el-option v-for="item in packageList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="renewVisible = false">{{$t('cancel')}}</el-button>
          <el-button type="primary" @click="submitPackageForm">{{$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 } from 'element-plus';
import * as API_BasicSetting from '@/api/basicSetting';
import * as API_Setting from '@/api/setting';
import * as API_Company from '@/api/company';
import * as API_Package from '@/api/package';
import Storage from '@/utils/storage';
import { useRouter, useRoute } from 'vue-router';
import { provinceAndCityData, pcTextArr, regionData, pcaTextArr, codeToText } from 'element-china-area-data';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus';

import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const route = useRoute();
const router = useRouter();
/* 营业执照 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  API_Company.checkLicense({ image_url: response.url }).then((res) => {
    companyForm.value.name = res.enterprise_name;
    companyForm.value.credit_code = res.credit_code;
    companyForm.value.license_msg = res;
    companyForm.value.license = response.url;
  });
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!');
    return false;
  }
  return true;
};
/* 身份证正面 */
const handleFrontSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  API_Company.checkIdCardOpposite({ image_url: response.url }, 'front').then((res) => {
    if (res.name !== companyForm.value.name) {
      ElMessage.error(t('upload_id_card')+'!');
      return;
    }
    companyForm.value.user_name = res.name;
    companyForm.value.id_card_msg_front = res;
    companyForm.value.id_card_front = response.url;
  });
};

const beforeFrontUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!');
    return false;
  }
  return true;
};
/* 身份证反面 */
const handleOppositeSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  API_Company.checkIdCardOpposite({ image_url: response.url }, 'opposite').then((res) => {
    companyForm.value.id_card_num = res.valid_date;
    companyForm.value.id_card_msg_opposite = res;
    companyForm.value.id_card_opposite = response.url;
  });
};

const beforeOppositeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('Avatar picture size can not exceed 10MB!');
    return false;
  }
  return true;
};

const uploadUrl = ref(import.meta.env.VITE_API_URL + '/uploaders');
const store = useStore();
const tableData = ref<any>({});
const loading = ref(false);
const dialogVisible = ref(false);
const companyForm = ref<any>({
  role_id: '',
  name: '',
  money: '',
  day: '',
  use_able: false,
  remark: '',
  address: '',
  license: '',
  company_package_id: '',
  license_msg: {},
  id_card_front: '',
  id_card_msg_front: {},
  id_card_opposite: '',
  id_card_msg_opposite: {},
});
const stockRules = ref<any>({
  role_id: [{ required: true, message: t('change')+t('package_role')+'!', trigger: 'change' }],
  name: [{ required: true, message:t('place')+t('companyName')+'!', trigger: 'blur' }],
  credit_code: [{ required: true, message:t('place')+t('credit_code')+'!', trigger: 'blur' }],
  industry: [{ required: true, message:t('place')+t('industry')+'!', trigger: 'blur' }],
  user_name: [{ required: true, message:t('place')+t('legal_person')+'!', trigger: 'blur' }],
  phone: [
    { required: true, message: t('place')+t('corporate_phone')+'!', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: t('valid_phone'), trigger: 'blur' },
  ],
  email: [
    { required: true, message:t('place')+t('companyEmail')+'!', trigger: 'blur' },
    { type: 'email', message:t('valid_email'), trigger: ['blur', 'change'] },
  ],
  postal_code: [
    { required: true, message:t('place')+t('postalCode')+'!', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}$/, message: t('valid_postal_code'), trigger: 'blur' },
  ],
});
const selectedOptions = ref<any[]>([]);
const marketingList = ref<any[]>([]);
const options = ref<any[]>(regionData);
const params = ref({
  data: [],
  page_no: 1,
  page_size: 10,
  keyword: '',
});
const roleArray = ref<any[]>([]);

const submitExamine = (value) => {
  companyForm.value.status = value;
  API_Company.superUpdateStatus(companyForm.value, companyForm.value.id).then((res) => {
    dialogVisible.value = false;
    ElMessage.success(t('audit_success')+'！');
    GET_CompanyList();
  });
};
const renewVisible = ref(false);
/* 套餐 */
const packageForm = ref<any>({
  company_package_id: '',
  this_money: '',
});
let packageId = ref('');
let companyId = ref('');
const packageFormRef = ref();

const disabled = ref(false);
const type = ref();
const handleBranch = (index: number, row: any) => {
  type.value = 'examine';
  companyForm.value = { ...row };
  disabled.value = true;
  selectedOptions.value = row.province;
  dialogVisible.value = true;
};

/* 续费 */
const handleRenew = (index: number, row: any) => {
  packageForm.value.company_package_id = row.company_package_id;
  companyId.value = row.id;
  packageId.value = row.company_package_id;
  API_Company.companyPackage(row.company_package_id).then((res) => {
    packageForm.value.this_money = res.money;
    renewVisible.value = true;
  });
};
const submitPackageForm = () => {
  packageFormRef.value.validate((valid: boolean) => {
    if (valid) {
      API_Company.difference(packageId.value).then((response) => {
        packageForm.value.this_money += response;
        API_Company.renewCompany(companyId.value, packageId.value).then((res) => {
          packageForm.value = {};
          packageId.value = '';
          if (packageId.value == packageForm.value.company_package_id) {
            ElMessage.success(t('renew_success'));
          } else {
            ElMessage.success(t('renew_info'));
          }
          renewVisible.value = false;
        });
      });
    }
  });
};
const companyFormRef = ref();
const checkPermission = (permissions: string[]): boolean => {
  // Implement your permission check logic here
  return true;
};

const handleAddWarehouse = () => {
  type.value = '';
  disabled.value = false;
  selectedOptions.value = [];
  companyForm.value = {};
  dialogVisible.value = true;
};

const handleEditWarehouse = (index: number, row: any) => {
  disabled.value = false;
  type.value = '';
  companyForm.value = { ...row };
  selectedOptions.value = row.province;
  console.log(companyForm);
  dialogVisible.value = true;
};

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

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

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

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

const submitWarehouseForm = () => {
  companyFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const { id } = companyForm.value;
      const params = { ...companyForm.value };
      params.province = selectedOptions.value.join(',');
      if (id) {
        API_Company.editCompany(id, params).then(() => {
          dialogVisible.value = false;
          ElMessage.success(t('edit_success')+'!');
          GET_CompanyList();
        });
      } else {
        API_Company.addCompany(params).then((res) => {
          dialogVisible.value = false;
          ElMessageBox.confirm(t('pass_error')+`:${res}`, t('prompt'), {
            confirmButtonText:  t('submit'),
            cancelButtonText:  t('cancel'),
            type: 'warning',
          })
            .then(() => {
              GET_CompanyList();
            })
            .catch(() => {
              /* Handle cancel action if needed */
            });
          /* ElMessage.success('添加成功！'); */
        });
      }
    } else {
      ElMessage.error(t('form_erroe'));
      /*    store.dispatch('showMessage', { message: '表单填写有误，请核对！', type: 'error' }); */
      return false;
    }
  });
};

const GET_CompanyList = () => {
  loading.value = true;
  API_Company.getPage(params.value)
    .then((response) => {
      loading.value = false;
      response.records.map((el: any) => {
        if (el.province !== undefined) {
          el.license = el.license.replace('blob:', '');
          el.province = el.province.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 packageList = ref<any>([]);
const GET_PackageList = () => {
  API_Package.packageList({ page_no: 1, page_size: 1000, use_able: true }).then((res) => {
    packageList.value = res.records;
  });
};

const packageName = (val) => {
  let name = '';
  packageList.value.map((el) => {
    if (el.id === val) {
      name = el.name;
    }
  });
  return name;
};
const adminName = (val: string[]) => {
  let text = '';
  console.log(val);
  if (val !== undefined) {
    text += codeToText[val[0]];
    text += codeToText[val[1]];
    text += codeToText[val[2]];
  }
  return text;
};

/* 切换菜单 */

const getBranch = (value, row) => {
  store.dispatch('toggleSuperMenu', value);
  store.dispatch('toggleCompanId', row.id);
  router.push({
    name: 'dashboard',
  });
};
const typeList = ref<any>([]);
const GET_Type = () => {
  API_Setting.getPage({ dictType: 'COMPANY_STATUS' }).then((res) => {
    typeList.value = res.data;
  });
};
const typeName = (value) => {
  let name = '';
  typeList.value.map((el) => {
    if (Number(el.value) === value) {
      name = el.label;
    }
  });
  return name;
};

onMounted(() => {
  GET_CompanyList();
  GET_MarketingList();
  GET_PackageList();
  GET_Type();
});
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 112px;
  height: 112px;
  text-align: center;
}
</style>
