<template>
  <cy-dialog ref="addStoreRef" title="绑定企业">
    <el-form class="rule-form-orange" :model="ruleForm">
      <el-form-item label="企业名称" style="width: 100%" class="form-required">
        <el-select v-model="ruleForm.enterpriseName" @change="enterpriseNameChange">
          <el-option
            v-for="item in allEnterpriseList"
            :label="item.name"
            :key="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="统一社会信用代码" style="width: 100%">
        <el-input v-model="ruleForm.socialCreditCode" placeholder="请输入统一信用代码" disabled></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button @click="handleCertain" type="primary">确 定</el-button>
    </div>
  </cy-dialog>
</template>

<script>
import { getAllEnterprise, bindEnterprise } from '@/api/myStoreEnterprise'

export default {
  props: {
    name: {
      type: String,
      default: ''
    },
    status: {
      type: [String, Number],
      default: ''
    },
    shopId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      ruleForm: {
        enterpriseName: '',
        socialCreditCode: ''
      },
      bindParams: {
        shopId: '',
        companyId: ''
      },
      allEnterpriseList: []
    }
  },
  methods: {
    initForm() {
      this.ruleForm.enterpriseName = ''
      this.ruleForm.socialCreditCode = ''
    },
    showAddEnterprise() {
      this.initForm()
      this.queryAllEnterprise()
      this.$refs.addStoreRef.show = true
    },
    enterpriseNameChange(val) {
      const find = this.allEnterpriseList.find(el => el.name === val)

      if (find) {
        this.ruleForm.socialCreditCode = find.code
        this.bindParams.companyId = find.id
      }
    },
    closeDialog() {
      this.$refs.addStoreRef.show = false
    },
    async queryAllEnterprise() {
      const res = await getAllEnterprise({ name: this.name, status: this.status })

      if (res.success && res.data.length) {
        this.allEnterpriseList = res.data
      }
    },
    async handleCertain() {
      this.bindParams.shopId = this.shopId
      if (!this.ruleForm.enterpriseName) {
        this.$message.warning('请选择要绑定的企业名称')
        return
      }
      if (!this.bindParams.shopId) {
        this.$message.warning('该企业没关联的店铺')
        return
      }
      if (!this.bindParams.companyId) {
        this.$message.warning('该企业不存在')
        return
      }

      const res = await bindEnterprise({ ...this.bindParams })

      if (res.success) {
        this.$message.success('企业绑定成功')
        this.closeDialog()
        this.$router.go(0)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.success-tip {
  width: 100%;
  height: 300px;
  line-height: 300px;
  font-size: #ebeb;
  padding-left: 100px;
}
</style>
