<template>
  <div class="edit-add-detail">
    <div class="crumbs">
      <Breadcrumb
        :breadcrumbOpt="breadcrumbOpt"
        svg-name="#icon-wodeqingqiu"
        @breadcrumb-click="handleClose"
      />
    </div>
    <div class="form-content">
      <el-form
        ref="formInfo"
        :model="parameter"
        label-width="auto"
        label-position="right"
        :rules="rules"
        v-loading="loading"
      >
        <template>
          <div class="rows">
            <div class="rows-left">
              <div class="rows-hr"></div>
            </div>
            <div class="rows-title">
              <div class="text-overflow">基本信息</div>
            </div>
          </div>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="企业名称" prop="enterpriseName">
                <el-input
                  v-model="parameter.enterpriseName"
                  placeholder=""
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="供应商名称" prop="supplierName">
                <el-input
                  clearable
                  prefix-icon="el-icon-search"
                  v-model="parameter.supplierName"
                  @focus="open('poolUnits')"
                  placeholder="请选择供应商"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="税号" prop="companyOrgcode">
                <el-input
                  readonly
                  v-model="parameter.companyOrgcode"
                  placeholder="选择供应商自动获取"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="准入规则编码" prop="admissionConfigCode">
                <el-input
                  v-model="parameter.admissionConfigCode"
                  @focus="openRule"
                  clearable
                  placeholder="请选择准入规则编码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="采购分类" prop="categoryCode">
                <el-cascader
                  ref="cascader"
                  @change="cascaderChange"
                  placeholder="请选择准入规则编码"
                  :options="matData"
                  disabled
                  v-model="parameter.categoryCode"
                  :props="{
                    value: 'code',
                    label: 'name',
                    checkStrictly: true,
                    emitPath: false,
                    multiple: true,
                  }"
                  style="width: 100%"
                ></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="资质类型" prop="qualificationsCodeList">
                <el-select
                  style="width: 100%"
                  @change="changeQua"
                  multiple
                  disabled
                  v-model="parameter.qualificationsCodeList"
                  placeholder="请选择准入规则编码"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
    </div>
    <div slot="footer" class="footer">
      <el-button @click="handleClose">{{ $t('domestic.cancel') }}</el-button>
      <el-button @click="handleSave" :loading="saveing" type="primary"
        >保存</el-button
      >
    </div>
    <expertPoolUnits
      @addDetail="(list) => addDetail(list, 'supplierList')"
      :useOrgList="supplierList"
      :needReturnKey="['code']"
      title="关联供应商"
      ref="poolUnits"
    />
    <rule-dialog
      ref="rules"
      @ruleData="getRule"
      :useOrgList="ruleList"
    ></rule-dialog>
  </div>
</template>
  
  <script>
import supplierManger from '@/api/supplierManger.js'
import dictUtils from '@/components/dict/DictSelectUtils.js'
import Breadcrumb from '@/components/Breadcrumb/index.vue'
import utils from '@/utils.js'
import expertPoolUnits from './expertPoolUnits.vue'
import ruleDialog from './ruleDialog.vue'
import classificationDialog from './classificationDialog.vue'
import multipleInput from '../../blacklistSupplier/component/multipleInput.vue'
export default {
  name: 'domesticDialog',
  components: {
    Breadcrumb,
    expertPoolUnits,
    ruleDialog,
    dictUtils,
    multipleInput,
    classificationDialog,
  },
  props: {
    editData: Object,
  },
  data() {
    return {
      saveing: false,
      breadcrumbOpt: [{breadcrumbName: '企业邀请'}, {breadcrumbName: '新增'}],
      rules: {
        enterpriseName: [
          {
            required: true,
            message: '请选择企业名称',
            trigger: ['blur', 'change'],
          },
        ],
        supplierName: [
          {
            required: true,
            message: '请选择供应商名称',
            trigger: ['blur', 'change'],
          },
        ],
        categoryName: [
          {
            required: true,
            message: '请选择供应商分类',
            trigger: ['blur', 'change'],
          },
        ],
        needProvideQualifications: [
          {
            required: true,
            message: '请选择资质',
            trigger: ['blur', 'change'],
          },
        ],
        // qualificationsCodeList: [
        //   {
        //     required: true,
        //     message: '请选择资质类型',
        //     trigger: ['blur', 'change'],
        //   },
        // ],
        // admissionConfigCode: [
        //   {
        //     required: true,
        //     message: '请选择准入规则编码',
        //     trigger: 'blur',
        //   },
        // ],
      },
      parameter: {
        type: 1,
        categoryCode: '',
        reviewStatus: 4,
        needProvideQualifications: 0,
        qualificationsCodeList: [],
        suppliersQualificationList: [],
        supplierTypeId: '',
        categoryName: '',
        admissionConfigCode: '',
        admissionConfigId: '',
      },
      options: [],
      list: [],
      suppliersQualificationList: [],
      enterpriseList: [],
      supplierList: [],
      loading: false,
      matData: [],
      ruleList: [],
    }
  },
  created() {
    this.currentUser = JSON.parse(sessionStorage.getItem('currentUserDetail'))
    this.parameter.enterpriseId = this.currentUser.org[0].orgId
    this.parameter.enterpriseName = this.currentUser.org[0].orgName
    this.parameter.enterpriseCode = this.currentUser.org[0].orgCode
    this.getMatClass()
    this.addModifyBtn()
    this.getQualification()
  },
  methods: {
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // 最后一级没有数据将children变成undefined
          delete data[i].children
        } else {
          // children不为空时继续调用该方法
          this.getTreeData(data[i].children)
        }
      }
      return data
    },
    // 获取企业物料分类
    getMatClass() {
      let params = {
        pageBean: {
          page: -1,
          pageSize: -1,
        },
      }
      this.$http
        .post(
          '${portal}/bizMaterialCategory/v1/getEnterpriseCategoryTree',
          params
        )
        .then((res) => {
          if (res.data.state) {
            this.matData = this.getTreeData(res.data.value)
          }
        })
    },
    open(type) {
      this.$refs[type].add()
    },
    deleteTags(index, key) {
      if (!index) {
        this[key] = []
      } else {
        this[key].splice(index, 1)
      }
      if (key === 'enterpriseList') {
        this.$set(this.parameter, 'enterpriseName', '')
        this.$set(this.parameter, 'enterpriseId', '')
        this.$set(this.parameter, 'enterpriseCode', '')
      }
      console.log(this.parameter)
    },
    addDetail(list, key) {
      console.log(list, key)
      this[key] = list
      if (key === 'enterpriseList') {
        this.$set(this.parameter, 'enterpriseName', list[0].name)
        this.$set(this.parameter, 'enterpriseId', list[0].id)
        this.$set(this.parameter, 'enterpriseCode', list[0].code)
      } else {
        let arr = []
        list.forEach((item) => {
          arr.push(item.name)
        })
        this.$set(this.parameter, 'supplierName', arr.join(','))
        console.log(this.parameter)
      }
      this.parameter.companyOrgcode = list[0].companyOrgcode
    },
    getByIdData(id) {
      supplierManger.getByIdManage(id).then((res) => {
        console.log(res, 'ress')
        this.loading = false
        let data = res.data
        this.enterpriseList = [
          {
            id: data.enterpriseId,
            code: data.enterpriseCode,
            name: data.enterpriseName,
          },
        ]
        this.supplierList = [
          {
            id: data.supplierId,
            code: data.supplierCode,
            name: data.supplierName,
          },
        ]
        this.parameter = data
        if (this.parameter.code == undefined) {
          this.parameter.code = ''
        }
        this.parameter.companyOrgcode = this.$route.query.rows.companyOrgcode
        if (this.parameter.suppliersQualificationList) {
          this.parameter.qualificationsCodeList =
            this.parameter.suppliersQualificationList.map((item) => {
              return item.qualificationCategoryCode
            })
        }
        this.parameter.categoryCode = this.parameter.categoryCode.split(',')
        this.parameter.qualificationsCodeList = Array.from(
          new Set(this.parameter.qualificationsCodeList)
        )
      })
    },
    getQualification() {
      let params = {
        pageBean: {
          page: -1,
          pageSize: -1,
        },
      }
      this.$http
        .post('${portal}/bizQualificationCategory/v1/page', params)
        .then((res) => {
          if (res.data.state) {
            let data = res.data.value.rows
            this.options = data
          }
        })
    },
    changeCode(val) {
      console.log(val, 'val')
      let data = dictUtils.getDictItemsFromCache('gysfl')
      data.forEach((item) => {
        if (item.value == val) {
          this.parameter.categoryName = item.name
        }
      })
    },
    cascaderChange(val) {
      this.parameter.categoryCode =
        this.$refs['cascader'].getCheckedNodes()[0].data.code
      this.parameter.categoryName =
        this.$refs['cascader'].getCheckedNodes()[0].data.name
      this.parameter.supplierTypeId =
        this.$refs['cascader'].getCheckedNodes()[0].data.id
    },
    getAdmission() {
      let params = {
        pageBean: {
          page: -1,
          pageSize: -1,
        },
        querys: [],
      }
      params.querys.push(
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'b.ENTERPRISE_ID_',
          relation: 'AND',
          value: this.parameter.enterpriseId,
        },
        {
          group: 'main',
          operation: 'IN',
          parentGroup: '',
          property: 'b.MAT_CATEGORY_ID_',
          relation: 'AND',
          value: this.parameter.supplierTypeId.split(','),
        }
      )
      this.suppliersQualificationList = []
      this.$http
        .post('${portal}/admissionConfigQualification/v1/queryByPage', params)
        .then((res) => {
          this.list = res.data.rows
          if (this.list.length != 0) {
            this.parameter.needProvideQualifications =
              this.list[0].necessaryStatus
            this.options = this.list
            // this.parameter.qualificationsCodeList = this.options.map((item) => {
            //   return item.code
            // })
            console.log(this.options, 'this.options ')
            this.options.forEach((item) => {
              this.suppliersQualificationList.push({
                qualificationCategoryId: item.id,
                qualificationCategoryCode: item.code,
                qualificationCategoryName: item.name,
                fileSize: item.fileSize,
                fileNum: item.fileNum,
              })
            })
          } else {
            this.parameter.needProvideQualifications = 0
            this.parameter.qualificationsCodeList = []
          }
        })
    },
    openRule() {
      this.$refs.rules.add(this.parameter)
    },
    getRule(data) {
      this.parameter.qualificationsCodeList = []
      this.ruleList = data
      this.parameter.admissionConfigCode = data
        .map((item) => {
          return item.code
        })
        .join(',')
      this.parameter.admissionConfigId = data
        .map((item) => {
          return item.id
        })
        .join(',')
      this.parameter.categoryName = data
        .map((item) => {
          return item.matCategoryName
        })
        .join(',')
      let code = data
        .map((item) => {
          return item.matCategoryCode
        })
        .join(',')
      this.parameter.categoryCode = code.split(',')
      this.parameter.supplierTypeId = data
        .map((item) => {
          return item.matCategoryId
        })
        .join(',')
      let qualificationList = []
      data.forEach((item) => {
        if (item.qualificationCategoryList.length != 0) {
          item.qualificationCategoryList.forEach((val) => {
            qualificationList.push(val)
          })
        }
      })
      qualificationList.forEach((item) => {
        this.parameter.qualificationsCodeList.push(item.code)
      })
      this.parameter.qualificationsCodeList = Array.from(
        new Set(this.parameter.qualificationsCodeList)
      )
      this.getAdmission()
      this.$forceUpdate()
    },
    changeStatus(val) {
      // if (val == 1) {
      //   this.parameter.reviewStatus = 4
      // } else {
      //   this.parameter.reviewStatus = 2
      // }
    },
    changeQua(val) {
      console.log(val)
      this.parameter.qualificationsCode = val.join(',')
      if (this.breadcrumbOpt[1].breadcrumbName === '编辑') {
        this.suppliersQualificationList = []
        this.options.forEach((item) => {
          val.forEach((v) => {
            if (item.code == v) {
              this.suppliersQualificationList.push({
                qualificationCategoryId: item.id,
                qualificationCategoryCode: item.code,
                qualificationCategoryName: item.name,
                fileSize: item.fileSize,
                fileNum: item.fileNum,
              })
            }
          })
        })
      } else {
        this.suppliersQualificationList = []
        this.options.forEach((item) => {
          val.forEach((v) => {
            if (item.code == v) {
              this.suppliersQualificationList.push({
                qualificationCategoryId: item.id,
                qualificationCategoryCode: item.code,
                qualificationCategoryName: item.name,
                fileSize: item.fileSize,
                fileNum: item.fileNum,
              })
            }
          })
        })
      }
      this.$forceUpdate()
    },
    //编辑
    addModifyBtn() {
      let id = this.$route.query.rows.id
      if (id) {
        this.loading = true
        this.getByIdData(id)
        this.breadcrumbOpt[1].breadcrumbName = '编辑'
      } else {
        this.breadcrumbOpt[1].breadcrumbName = '新增'
      }
    },
    // 关闭//面包屑点击
    handleClose() {
      if (this.breadcrumbOpt[1].breadcrumbName === '编辑') {
        this.$router.push({
          name: 'enterpriseInvitation',
          params: {
            pageBean: this.$route.query.pageBean,
          },
        })
      } else {
        this.$router.push({
          name: 'enterpriseInvitation',
        })
      }
      this.active = 0
      // this.$emit('closeComponent')
      this.parameter = {}
      // this.$refs.formInfo.clearValidate()
    },
    // 保存
    handleSave() {
      // if (this.parameter.needProvideQualifications == 1) {
      //   this.parameter.reviewStatus = 0
      // } else {
      //   this.parameter.reviewStatus = 2
      // }
      if (this.parameter.categoryCode.length) {
        this.parameter.categoryCode = this.parameter.categoryCode.toString()
      }
      console.log(this.parameter)
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          this.saveing = true
          if (this.suppliersQualificationList.length != 0) {
            this.parameter.suppliersQualificationList =
              this.suppliersQualificationList
          }
          let params = {
            ...this.parameter,
            supplierList: this.supplierList,
          }
          supplierManger.saveManage(params).then((res) => {
            this.saveing = false
            if (res.data.state) {
              this.$confirm('保存成功，是否返回列表页?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success',
              }).then(() => {
                this.$router.push({
                  name: 'enterpriseInvitation',
                })
              })
            } else {
              this.loading = false
              this.$message.error('保存失败！')
            }
          })
        }
      })
    },
  },
}
</script>
  
  <style lang="scss"
    scoped>
/deep/ .el-row {
  padding: 0 240px;
}

// 步骤条
.theSteps {
  background-color: white;
  padding: 10px;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  margin-top: 10px;

  /deep/.el-steps {
    width: 50%;
  }

  /deep/.el-steps--simple {
    background-color: rgba($color: #000000, $alpha: 0);
  }
}

.rows {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ebebeb;
  margin-bottom: 16px;
  padding: 10px 0;

  .rows-left {
    margin-right: 10px;

    .rows-hr {
      width: 3px;
      height: 18px;
      background-color: #0e6eff;
      border-radius: 2px;
    }
  }

  .rows-title {
    .text-overflow {
      width: 100%;
      font-size: 16px;
    }
  }
}
</style>
  