<template>
  <div style="background: #fff; padding: 10px 0">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="200px"
      size="small"
    >
      <el-form-item label="企业logo：" prop="logo">
        <UploadQiniu
          :file-list="img_list"
          @uploadSuccess="uploadSuccess"
          @handleRemove="uploadRemove"
        />
      </el-form-item>
      <el-form-item label="品牌名称：">
        <el-input
          v-model="form.brandName"
          placeholder="请输入品牌名称"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="企业名称：" prop="enterpriseName">
        <el-input
          v-model="form.enterpriseName"
          placeholder="请输入企业名称"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="!isEdit" label="到期时间：" prop="expireTime">
        <el-date-picker
          v-model="form.expireTime"
          type="datetime"
          style="width: 300px"
          placeholder="选择日期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="店铺类型：" prop="scope">
        <el-radio-group v-model="form.scope" :disabled="!!isEdit">
          <el-radio :label="4">单店铺</el-radio>
          <el-radio :label="5">连锁店</el-radio>
        </el-radio-group>
        <p style="font-size: 12px; color: #f5762c">
          企业创建成功后，店铺类型不允许修改切换，请谨慎操作！！！
        </p>
      </el-form-item>
      <el-form-item label="联系人：" prop="contact">
        <el-input
          v-model="form.contact"
          placeholder="请输入联系人"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系电话：" prop="mobile">
        <el-input
          v-model="form.mobile"
          placeholder="请输入联系电话"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属区域：" prop="provinceCode">
        <span v-if="enterpriseId">
          <RegionSelect
            v-if="region.length"
            v-model="region"
            style="width: 300px"
            @change="regionChange"
          />
        </span>
        <span v-else>
          <RegionSelect
            v-model="region"
            style="width: 300px"
            @change="regionChange"
          />
        </span>
      </el-form-item>
      <el-form-item label="详细地址：" prop="address">
        <el-input
          v-model="form.address"
          placeholder="请输入详细地址"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="sub_loading" type="primary" @click="submitData">
          {{ enterpriseId ? "保存" : "立即创建" }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import RegionSelect from "@/component/common/RegionSelectJSON";
  import UploadQiniu from "@/component/common/UploadQiniuBtn.vue";
  import {
    // getAllEnterpriseCategory,
    getEnterpriseInfo,
    updateEnterprise,
    addEnterprise,
    getAclList,
    getStaffByToken,
  } from "@/api/user";
  import { mapActions } from "vuex";
  import router from "@/router";
  export default {
    name: "CreateStore",
    components: {
      RegionSelect,
      UploadQiniu,
    },
    props: {
      enterpriseId: {
        type: [Number, String],
        default: 0,
      },
      isAvatar: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        sub_loading: false,
        isEdit: false,
        img_list: [],
        options: [],
        dialogImageUrl: "",
        dialogVisible: false,
        region: [],
        endTime: "",
        startTime: "",
        form: {
          scope: "", // 5:多店铺（默认）  4:单店铺）
          brandName: "",
          enterpriseName: "",
          contact: "",
          mobile: "",
          provinceCode: "",
          cityCode: "",
          districtCode: "",
          address: "",
          categoryId: "", //企业类别
          startTime: "",
          endTime: "",
          expireTime:'',//到期时间
          logo: "",
        },
        rules: {
          scope: [
            { required: true, message: "请选择店铺类型", trigger: "change" },
          ],
          enterpriseName: [
            { required: true, message: "请输入企业名称", trigger: "blur" },
          ],
          expireTime: [
            { required: true, message: "请选择到期时间", trigger: "blur" },
          ],
          contact: [
            { required: true, message: "请输入联系人", trigger: "blur" },
          ],
          mobile: [
            { required: true, message: "请输入联系电话", trigger: "blur" },
            {
              min: 11,
              max: 11,
              message: "长度在11个字符",
              trigger: "blur",
            },
          ],
          provinceCode: [
            { required: true, message: "请选择所属区域", trigger: "change" },
          ],

          address: [
            { required: true, message: "请输入详细地址", trigger: "change" },
          ],

          categoryId: [
            { required: true, message: "请选择企业类别", trigger: "change" },
          ],
          logo: [
            { required: true, message: "请上传企业LOGO", trigger: "change" },
          ],
        },
        enterprise_detail: {},
      };
    },
    async mounted() {
      if (this.enterpriseId || this.$route.params.id) {
        console.log(this.enterpriseId,'00000000000');
        this.isEdit = !!(this.enterpriseId || this.$route.params.id);
        await this.getEnterpriseInfo();
      }
    },
    methods: {
      ...mapActions({
        setAccessToken: "user/setAccessToken",
        setEnToken: "user/setEnToken",
        changeExpireTime: "MUser/changeExpireTime",
        changeUserName: "MUser/changeUserName",
        changeShelfLifeSetUp: "MUser/changeShelfLifeSetUp",
        changeUserCenterId: "MUser/changeUserCenterId",
        changeEnterpriseScope: "MUser/changeEnterpriseScope",
        changeEnterprise: "MUser/changeEnterprise",
      }),

      // 选择图片
      uploadSuccess(val, res, file, fileList) {
        this.form.logo = val;
      },
      uploadRemove() {
        this.form.logo = "";
      },
      //  获取企业类别
      // async getAllEnterpriseCategory() {
      //   const { data } = await getAllEnterpriseCategory();
      //
      //   this.options = data;
      // },
      //  企业详情
      async getEnterpriseInfo() {
        const { data } = await getEnterpriseInfo();

        this.enterprise_detail = data;
        this.region = [data.provinceCode, data.cityCode, data.districtCode];
        this.img_list = [
          {
            name: "",
            url: data.logo,
          },
        ];
        this.form = {
          scope: data.scope,
          brandName: data.brandName,
          enterpriseName: data.enterpriseName,
          contact: data.contact,
          mobile: data.mobile,
          provinceCode: data.provinceCode,
          cityCode: data.cityCode,
          districtCode: data.districtCode,
          address: data.address,
          expireTime:new Date(parseInt(data.expireTime) * 1000),
          logo: data.logo,
        };
      },
      cancel() {
        this.$router.push("/Enterprise");
        this.$emit("cancel");
      },
      // 提交
      submitData() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            this.sub_loading = true;
            if (this.isEdit) {
              try {
                const { data } = await updateEnterprise({
                  ...this.form,
                });
                this.sub_loading = false;
                this.$message({
                  type: "success",
                  message: "提交成功",
                });
                this.$emit("confirm");
                if (this.$route.params.id) {
                  const obj = {
                    userCenterId: this.enterprise_detail.userCenterId,
                    enterpriseId: this.enterprise_detail.enterpriseId,
                    roleType: sessionStorage.getItem("roleType") || 1,
                    enterpriseName: this.form.enterpriseName,
                    logo: this.form.logo,
                    token: this.enterprise_detail.token,
                    scope: this.form.scope,
                    expireStatus:
                      new Date().getTime() <=
                      this.enterprise_detail.endTime * 1000,
                    shelfLifeSetUp: parseInt(
                      this.$store.getters["MUser/shelfLifeSetUp"]
                    ),
                  };
                  await this.goEnterprise(obj);
                }
              } finally {
                this.sub_loading = false;
              }
            } else {
              try {
                const { data } = await addEnterprise({
                  ...this.form,
                });
                this.sub_loading = false;
                this.$message({
                  type: "success",
                  message: "提交成功",
                });
                const obj = {
                  userCenterId: data.userCenterId,
                  enterpriseId: data.enterpriseId,
                  enterpriseName: data.enterpriseName,
                  logo: data.logo,
                  token: data.token,
                  scope: data.scope,
                  expireStatus: false,
                  shelfLifeSetUp: 4,
                  roleType: 1,
                };
                await this.goEnterprise(obj);
                this.$emit("confirm");
              } finally {
                this.sub_loading = false;
              }
            }
            // this.centerDialogVisible = false;

            // this.$router.push("/Enterprise");
          }
        });
      },
      // 进入企业
      async goEnterprise(row) {
        const Loading = this.$baseColorfullLoading(1, "正在进入企业...");
        this.setEnToken(row.token);
        /*const { data } = await createToken({
          userCenterId: row.userCenterId,
        });
        // 重新生成token
        this.setAccessToken(data.token);*/
        // 保存店铺类型 区分单店和连锁
        this.changeEnterpriseScope(row.scope);
        this.changeEnterprise(row);
        this.changeExpireTime(row.expireTime);
        this.changeShelfLifeSetUp(row.shelfLifeSetUp);

        sessionStorage.setItem("roleType", row.roleType);

        await this.$store.dispatch("user/getUserInfo", row.roleType);
        await this.getAclList(row.roleType);
        await this.getStaffByToken(row.roleType);
        Loading.close();
      },
      // 获取当前登录员工信息
      async getStaffByToken(roleType) {
        const { data } = await getStaffByToken(roleType);
        if (data.name) {
          this.changeUserName(data.name);
        }
        this.changeUserCenterId(data.userCenterId);
        if (!this.$route.params.isCashier) {
          await this.$router.push(`/`);
        } else {
          this.$router.push(`/CashierShop/CashierShop`);
        }
      },
      // 获取员工权限
      async getAclList(roleType) {
        const { data } = await getAclList(roleType);
        sessionStorage.setItem("dataField", JSON.stringify(data.dataField));
        sessionStorage.setItem("isSuper", data.isAdministrator);
        sessionStorage.setItem("nodes", JSON.stringify(data.custom));

        // 进入企业设置，根据权限设置菜单
        let accessRoutes = await this.$store.dispatch("routes/setRoutes");
        router.addRoutes(accessRoutes);
      },
      // 选择区域
      regionChange(val) {
        this.form.provinceCode = val[0];
        this.form.cityCode = val[1];
        this.form.districtCode = val[2];
      },
      //  选择企业类型
      // categoryChange(val) {
      //   this.form.categoryId = val;
      // },
      loginOut() {
        sessionStorage.clear();
        this.$store.dispatch("MUser/changeSystemType", 1);
        this.$store.dispatch("user/logout");
        this.$router.push("/login");
      },
    },
  };
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    /*line-height: 178px;*/
    transform: translateY(75px);
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
