<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="12vh"
    width="600px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    append-to-body
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="showModelThis = false"
  >
    <el-card style="margin-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            label-position="right"
            label-width="110px"
            :model="ruleForm"
            :rules="rulesThis"
            size="mini"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item label="组织/企业：" prop="region" v-if="organName">
                  <el-select
                    v-model="ruleForm.region"
                    style="width: 100%"
                    :disabled="isDetail !== '003'"
                    placeholder="组织/企业"
                  >
                    <el-option label="组织" value="0" />
                    <el-option label="企业" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="上级组织">
                  <el-input
                    v-model="organName"
                    disabled
                    :placeholder="organName ? '上级组织' : '暂无上级组织'"
                    maxlength="100"
                  />
                </el-form-item>
              </el-col>

              <el-col v-if="ruleForm.region === '0'" :span="24">
                <el-form-item label="组织名称：" prop="name">
                  <el-input
                    style="width:100%"
                    v-model="ruleForm.name"
                    :disabled="isDetail === '001'"
                    placeholder="组织名称"
                    maxlength="50"
                  ><template v-if="organName" slot="prepend">{{
                    organName
                  }}</template></el-input>
                </el-form-item>
              </el-col>
              <el-col v-if="ruleForm.region === '1'" :span="24">
                <el-form-item label="企业名称：" prop="companyName">
                  <el-input
                    v-model="ruleForm.companyName"
                    :disabled="isDetail === '001'"
                    placeholder="企业名称"
                    maxlength="50"
                  ><template v-if="organName" slot="prepend">{{
                    organName
                  }}</template></el-input>
                </el-form-item>
              </el-col>
              <el-col
                v-if="ruleForm.region === '1'"
                :span="24"
                style="padding: 0 0 16px 0"
              >
              </el-col>
              <el-col :span="24" style="text-align: right">
                <el-button
                  v-if="isDetail !== '007'"
                  size="mini"
                  type="primary"
                  @click="submitForm"
                >保 存
                </el-button>
                <el-button size="mini" @click="showModelThis = false">{{
                  isDetail == "007" ? "关 闭" : "取 消"
                }}</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import resToken from '@/mixins/resToken'
import asyncRequest from "@/apis/service/serviceParam/organize";
import contactModal from './contactModal'
export default {
  name: 'GoodsBack',
  components: {
    contactModal
  },
  mixins: [resToken],
  props: ['showModel', 'isDetail', 'id', 'organ', 'kh', "sitem"],
  data() {
    const validator = function(rule, value, callback) {
      const isValueValid = Array.isArray(value) && value.length > 0
      if (!isValueValid && this.area !== '0') {
        callback(new Error('企业所在区域不能为空'))
      } else {
        callback()
      }
    }

    return {
      area: '',
      findex: -1,
      sitem: null,
      editModel: false,
      loading: false,
      title: '添加企业/组织',
      showModelThis: this.showModel,
      ruleForm: {},
      rulesThis: this.rules,
      organName: '',
      tableData: [],
      old_tableData: [],
      branch: '',
      middle: '',
      rules: {
        region: [
          {
            required: true,
            message: '请选择组织/企业',
            trigger: 'change'
          }
        ],
        name: [
          {
            required: true,
            message: '组织名称不能为空',
            trigger: 'blur'
          }
        ],
        companyName: [
          {
            required: true,
            message: '企业名称不能为空',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    },
    area(val) {
      if (val) {
        this.ruleForm.code = ''
        this.branch = ''
        this.middle = ''
      }
    },
    'ruleForm.code': {
      handler(val) {
        if (val) this.area = ''
      },
      deep: true
    }
  },
  methods: {
    handleFreedomAreaChange() {
      this.$nextTick(() => this.$refs.ruleForm.validateField('code'))
    },
    async initForm() {
      this.loading = true
      this.tableData = []
      this.old_tableData = []
      this.organName = ''
      await this.resetForm()
      if (this.isDetail === '003') {
        this.title = '添加企业/组织'
        this.rulesThis = this.rules
      } else if (this.isDetail === '005') {
        this.title = '修改企业/组织'
        this.rulesThis = this.rules
        await this.initData()
      } else {
        this.title = '查看企业/组织'
        this.rulesThis = {}
        await this.initData()
      }
      this.setOrganName()
      this.loading = false
    },
    setOrganName() {
      this.organName = ''
      if (this.organ && this.organ.length > 1) {
        this.organ.forEach((e) => {
          if (e.id !== '0') {
            this.organName += e.name
            this.ruleForm.pid = e.id
          }
        })
      } else {
        this.organName = ''
      }
    },
    openEdit(index, sitem) {
      this.findex = index
      this.sitem = sitem
      this.editModel = true
    },
    openDelete(index) {
      this.tableData.splice(index, 1)
    },
    async resetForm() {
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          this.ruleForm = {
            id: '',
            pid: '0',
            region: '0',
            name: '',
            code: [],
            area: ''
          }
        }
      })
    },
    async initData() {
      console.log(this.sitem)
      // this.ruleForm = {
      //   id: id,
      //   region: this.kh + '' || '0',
      //   pid: parent || pid || '0',
      //   name: name || '',
      //   companyName: companyName || '',
      //   code: isFreedom || !middle ? [] : [middle],
      //   area: area ? [area] : []
      // }

      const {
        id,
        name
      } = this.sitem

      this.ruleForm = {
        id: id || "",
        name: name || "",
        region: this.kh + '' || '0'
      }
    },
    contactRefresh(e) {
      this.editModel = false
      const {
        index,
        contactor,
        commobile,
        position,
        comdepart,
        wxaccount,
        qqaccount,
        email,
        id,
        is_del
      } = e
      if (index + '' === '-1') {
        this.tableData.push(e)
      } else {
        const findex = parseInt(index)
        this.tableData[findex].contactor = contactor || ''
        this.tableData[findex].commobile = commobile || ''
        this.tableData[findex].position = position || ''
        this.tableData[findex].comdepart = comdepart || ''
        this.tableData[findex].wxaccount = wxaccount || ''
        this.tableData[findex].qqaccount = qqaccount || ''
        this.tableData[findex].email = email || ''
        this.tableData[findex].id = id || ''
        this.tableData[findex].is_del = is_del || '0'
      }
    },
    areasearchChange(e) {
      const { id, city_code, province_code, label } = e
      this.ruleForm.code = e && id ? [id] : []
      this.ruleForm.area = e && id ? label : ''
      this.ruleForm.branch = e && id ? province_code : ''
      this.ruleForm.middle = e && id ? city_code : ''

      this.branch = province_code
      this.middle = city_code

      this.$refs.ruleForm.validateField('code')
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (this.loading) {
            return
          }
          this.loading = true
          const { id, pid, name, code: area_code, area } = this.ruleForm
          let res = {}
          if (this.ruleForm.region === '0') {
            const zitem = {
              id: id,
              pid: pid,
              name: name
            }
            if (this.isDetail === '003') {
              delete zitem['id']
              res = await asyncRequest.zadd(zitem)
            } else {
              res = await asyncRequest.zupdate(zitem)
            }
          } else {
            const qitem = {
              id: id,
              itemid: pid,
              companyName: this.ruleForm.companyName
            }
            if (this.isDetail === '003') {
              delete qitem['id']
              res = await asyncRequest.qadd(qitem)
            } else {
              res = await asyncRequest.qupdate(qitem)
            }
          }
          this.loading = false
          const { code } = res
          if (code === 1) {
            const title = this.isDetail === '003' ? '添加成功!' : '修改成功!'
            this.$notify.success({
              title,
              message: ''
            })
            this.showModelThis = false
            // 刷新
            this.$emit('refresh')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getCustomer() {
      const list = JSON.parse(JSON.stringify(this.tableData))
      const oldlist = JSON.parse(JSON.stringify(this.old_tableData))
      const hasIDlist = []
      list.forEach((a) => {
        if (a.id !== '') {
          hasIDlist.push(a)
        }
      })
      const newList = []
      const resList = []
      oldlist.forEach((a, ai) => {
        let item = null
        const index = hasIDlist.findIndex((b) => a.id + '' === b.id + '')
        if (index === -1) {
          item = JSON.parse(JSON.stringify(a))
          item.is_del = '1'
        } else {
          item = JSON.parse(JSON.stringify(hasIDlist[index]))
        }
        newList.push(item)
      })
      list.forEach((b) => {
        if (b.id === '') {
          b.is_del = '0'
          newList.push(b)
        }
      })
      newList.forEach((a) => {
        const m = {
          id: a.id,
          contactor: a.contactor,
          position: a.position,
          commobile: a.commobile,
          comdepart: a.comdepart,
          wxaccount: a.wxaccount,
          qqaccount: a.qqaccount,
          email: a.email,
          is_del: a.is_del || '0',
          status: a.status || '1'
        }
        resList.push(m)
      })

      return resList
    }
  }
}
</script>

<style lang="scss" scoped>
.storeAnomaly {}
</style>
