<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-dialogDrag
      width="1200px"
      height="500px"
      @close="close"
      append-to-body
      @keyup.enter.native=""
      :visible.sync="visible">
      <el-row>
        <el-form size="middle" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method === 'view'"
                 label-width="140px" @submit.native.prevent>
          <el-row  :gutter="0">
            <el-col :span="10">
              <el-form-item label="供应商名称" prop="name" :rules="[
                  {required: true, message:'请填写供应商名称', trigger:'blur'}
                   ]">
<!--                <span slot="label"><span style="color: red;border-top: 20px">*</span> 供应商名称</span>-->
                <el-input maxlength="64" v-model="inputForm.name" @input="checkName" @blur="checkName" placeholder="请输入供应商名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-popover
                v-model="visiblePop"
                placement="left"
                width="400"
                height="800"
                trigger="click"
                :popper-options="{ boundariesElement: 'viewport', removeOnDestroy: true }"
                ref="pops">
                <vxe-table
                  border="inner"
                  auto-resize
                  resizable
                  :row-config="{isHover: true}"
                  :data="gridData"
                  :checkbox-config="{}"
                  :row-style="rowStyle"
                  :key="popKey"
                  @cell-click="rowClick"
                  :show-header="false"
                >
                  <vxe-column title="" field="entname" ></vxe-column>
                </vxe-table>

                <el-button type="info" slot="reference" @click="getPopTable" style="width: 100%" plain>查询</el-button>

              </el-popover>
              <el-form-item>

              </el-form-item>
            </el-col>

<!--            <el-col :span="12">-->
<!--              <el-form-item label="供应商名称" prop="name" :rules="[-->
<!--                      {required: true, message:'供应商名称不能为空', trigger:'blur'}-->
<!--                   ]">-->
<!--                <el-input maxlength="64" v-model="inputForm.name" placeholder="请输入供应商名称"></el-input>-->
<!--              </el-form-item>-->
<!--            </el-col>-->

            <el-col :span="12">
              <el-form-item label="是否拥有信用代码" prop="isUscCode"
                            :rules="[
                    {required: true, message:'请选择是否拥有信用代码', trigger:'blur'}
                   ]">
                <el-radio-group v-model="inputForm.isUscCode">
                  <el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" >{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col v-if="inputForm.isUscCode === '1'" :span="12">
              <el-form-item label="统一社会信用代码" prop="uscCode"
                            :rules="[
                                    {required: true, message:'统一社会信用代码不能为空', trigger:'blur'}
                     ]">
                <el-input v-model="inputForm.uscCode" placeholder="请填写统一社会信用代码" ></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="inputForm.isUscCode === '0'||commonJS.isEmpty(inputForm.isUscCode)" :span="12">
              <el-form-item label="统一社会信用代码" prop="uscCode"
                            :rules="[
                     ]">
                <el-input v-model="inputForm.uscCode" placeholder="请填写统一社会信用代码" ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归属地区" prop="reconciliationArea"
                            :rules="[
                 ]">
                <SelectTree
                  ref="areaTree"
                  :props="{
                      value: 'id',             // ID字段名
                      label: 'name',         // 显示名称
                      children: 'children'    // 子级字段名
                    }"
                  url="/sys/area/treeData"
                  :value="inputForm.reconciliationArea"
                  :clearable="true"
                  size="medium"
                  :accordion="true"
                  @getValue="(value) => {inputForm.reconciliationArea=value}"/>
              </el-form-item>
            </el-col>
<!--            <el-col :span="12">-->
<!--              <el-form-item label="供应商性质" prop="characterIs"-->
<!--                            :rules="[-->
<!--                     ]">-->
<!--                <el-select v-model="inputForm.characterIs" placeholder="请选择供应商性质" style="width: 100%;">-->
<!--                  <el-option-->
<!--                    v-for="item in $dictUtils.getDictList('cw_work_client_type')"-->
<!--                    :key="item.value"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value">-->
<!--                  </el-option>-->
<!--                </el-select>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="邮政编码" prop="zipCode">
                <el-input maxlength="64" v-model="inputForm.zipCode" placeholder="请填写邮政编码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="传真" prop="fax">
                <el-input maxlength="64" v-model="inputForm.fax" placeholder="请填写传真"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="telPhone"
                            :rules="[
                     ]">
                <el-input v-model="inputForm.telPhone" placeholder="联系电话" ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址" prop="address"
                            :rules="[
                     ]">
                <el-input v-model="inputForm.address" placeholder="地址" ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks"
                            :rules="[
                     ]">
                <el-input type="textarea" style="width:100%" :rows="5" maxlength="500" v-model="inputForm.remarks" placeholder="请填写备注"></el-input>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </el-row>
      <!--    联系人信息-->
      <el-divider content-position="left">
        <i class="el-icon-document"></i>
        联系人信息
        <el-button style="margin-left: 20px" type="primary" :disabled="method==='view'" size="mini" @click="insertEvent('link')" plain>
          新增
        </el-button>
      </el-divider>
      <el-row  :gutter="15">
        <vxe-table
          border
          :column-config="{resizable: true}"
          show-overflow
          show-footer
          :key="tableKey"
          ref="linkTable"
          class="vxe-table-element"
          :data="inputForm.materialSupplierLinkDTOList"
          style="margin-left: 3em"
          @cell-click=""
          @edit-closed=""
          highlight-current-row
          :edit-rules="validRules"
          :edit-config="{trigger: 'click', mode: 'row', showStatus: false, autoClear: true, icon: '-', activeMethod: activeRowMethod}"
        >
          <vxe-table-column align="center" field="name" title="姓名" :edit-render="{}">
            <template v-slot:edit="scope">
              <vxe-input v-model="scope.row.name" placeholder="姓名"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column align="center" field="sex" title="性别" :edit-render="{name: '$select', options: $dictUtils.getDictList('sex')}">
            <template v-slot:edit="scope">
              <vxe-select v-model="scope.row.sex" placeholder="性别" style="width: 100%;" transfer>
                <vxe-option
                  v-for="item in $dictUtils.getDictList('sex')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </vxe-option>
              </vxe-select>
            </template>
          </vxe-table-column>
          <vxe-table-column align="center" field="office" title="部门" :edit-render="{}">
            <template v-slot:edit="scope">
              <vxe-input v-model="scope.row.office" placeholder="部门"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column align="center" field="position" title="职务" :edit-render="{}">
            <template v-slot:edit="scope">
              <vxe-input v-model="scope.row.position" placeholder="职务" ></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column align="center" field="linkPhone" title="联系方式1" :edit-render="{}">
            <template v-slot:edit="scope">
              <vxe-input v-model="scope.row.linkPhone" oninput="value=value.replace(/[^\d]/g,'')" placeholder="联系方式1" ></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column align="center" field="linkMobile" title="联系方式2" :edit-render="{}">
            <template v-slot:edit="scope">
              <vxe-input v-model="scope.row.linkMobile" oninput="value=value.replace(/[^\d]/g,'')" placeholder="联系方式2" ></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column align="center" field="email" title="邮箱" :edit-render="{}">
            <template v-slot:edit="scope">
              <vxe-input v-model="scope.row.email" @change="$forceUpdate()" @blur="blurEmail(scope.$rowIndex)" placeholder="邮箱"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column align="center" field="remarks" title="备注" :edit-render="{}">
            <template v-slot:edit="scope">
              <vxe-input maxlength="500" v-model="scope.row.remarks" placeholder="备注"></vxe-input>
            </template>
          </vxe-table-column>
          <vxe-table-column align="center" title="操作" width="100">
            <template v-slot="scope">
              <el-button :disabled="method === 'view'" size="mini" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'link')">删除</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
      </el-row>
      <!--    附件-->
      <UpLoadComponent ref="uploadComponent"></UpLoadComponent>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" :loading="loading" @click="close()" icon="el-icon-circle-close">关闭</el-button>
        <el-button size="small" :loading="loading" v-if="method === 'edit' || method === 'add'" type="primary" icon="el-icon-circle-check" @click="save()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import UpLoadComponent from '@/views/common/UpLoadComponent'
  import SupplierService from '@/api/materialManagement/SupplierService'
  import EnterpriseSearchService from '@/api/cw/common/EnterpriseSearchService'
  export default {
    data () {
      return {
        title: '',
        method: '',
        loading: false,
        inputForm: {
          name: '',
          isUscCode: '',
          uscCode: '',
          reconciliationArea: '',
          characterIs: '',
          zipCode: '',
          fax: '',
          telPhone: '',
          address: '',
          remarks: '',
          materialSupplierLinkDTOList: [],
          workAttachmentDtoList: []
        },
        tableKey: '',
        visible: false,
        visiblePop: false,
        validRules: {
          name: [
            {required: true, message: '姓名不可以为空'}
          ],
          linkPhone: [
            {required: true, message: '联系方式1不可以为空'}
          ]
        },
        gridData: [],
        popKey: ''
      }
    },
    supplierService: null,
    enterpriseSearchService: null,
    created () {
      this.supplierService = new SupplierService()
      this.enterpriseSearchService = new EnterpriseSearchService()
    },
    components: {
      UpLoadComponent,
      SelectTree
    },
    methods: {
      init (method, id) {
        if (method === 'add') {
          this.title = '新建供应商信息'
        } else if (method === 'edit') {
          this.title = '修改供应商信息'
        } else {
          method = 'view'
          this.title = '查看供应商信息'
        }
        this.visible = true
        this.method = method
        this.inputForm = {
          name: '',
          isUscCode: '',
          uscCode: '',
          reconciliationArea: '',
          characterIs: '',
          zipCode: '',
          fax: '',
          telPhone: '',
          address: '',
          remarks: '',
          materialSupplierLinkDTOList: [],
          workAttachmentDtoList: []
        }
        this.inputForm.id = id
        if (this.commonJS.isEmpty(this.inputForm.id)) {
          this.inputForm.id = 'false'
        }
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.supplierService.queryById(this.inputForm.id).then(({data}) => {
            this.$refs.uploadComponent.clearUpload()
            this.inputForm = this.recover(this.inputForm, data)
            this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
            if (this.commonJS.isEmpty(this.inputForm.isUscCode)) {
              this.inputForm.isUscCode = '0'
            }
            if (this.commonJS.isEmpty(this.inputForm.materialSupplierLinkDTOList)) {
              this.inputForm.materialSupplierLinkDTOList = []
            }
            if (this.commonJS.isEmpty(this.inputForm.workAttachmentDtoList)) {
              this.inputForm.workAttachmentDtoList = []
            }
            this.$refs.uploadComponent.newUpload(this.method, this.inputForm.workAttachmentDtoList, 'material_supplier')
            this.loading = false
          })
        })
      },
      save () {
        this.$refs['inputForm'].validate(async (valid) => {
          if (valid) {
            if (this.commonJS.isEmpty(this.inputForm.materialSupplierLinkDTOList)) {
              // this.$message.error('联系人信息至少填写一条')
              this.saveTrue()
            } else {
              const errMap = await this.$refs.linkTable.validate(true).catch(errMap => errMap)
              if (errMap) {
                this.$message.error('联系人信息填写不正确')
              } else {
                this.supplierService.findByName(this.inputForm.name).then(({data}) => {
                  if (this.commonJS.isNotEmpty(data) && this.commonJS.isNotEmpty(data.name)) { // 说明有查询到这个名称的数据
                    if ((this.commonJS.isNotEmpty(this.inputForm.id) && this.inputForm.id !== data.id) || this.commonJS.isEmpty(this.inputForm.id)) {
                      this.$message.warning('供应商已存在')
                    } else {
                      this.saveTrue()
                    }
                  } else {
                    this.saveTrue()
                  }
                })
              }
            }
          }
        })
      },
      saveTrue () {
        this.loading = true
        if (this.$refs.uploadComponent.checkProgress()) {
          this.loading = false
        } else {
          this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
          this.supplierService.save(this.inputForm).then(() => {
            this.loading = false
            this.$emit('refreshList')
            this.close()
          }).catch(() => {
            this.loading = false
          })
        }
      },
      close () {
        this.inputForm = {
          name: '',
          isUscCode: '',
          uscCode: '',
          reconciliationArea: '',
          characterIs: '',
          zipCode: '',
          fax: '',
          telPhone: '',
          address: '',
          remarks: '',
          materialSupplierLinkDTOList: [],
          workAttachmentDtoList: []
        }
        this.$refs.uploadComponent.clearUpload()
        this.$refs.inputForm.resetFields()
        this.visible = false
      },
      // 新增
      insertEvent (type) {
        if (type === 'link') {
          let d = {
            name: '',
            office: '',
            position: '',
            sex: '',
            linkPhone: '',
            linkMobile: '',
            email: ''
          }
          if (this.commonJS.isEmpty(this.inputForm.materialSupplierLinkDTOList)) {
            this.inputForm.materialSupplierLinkDTOList = []
          }
          this.$refs.linkTable.insertAt(d)
          this.inputForm.materialSupplierLinkDTOList.push(d)
          this.tableKey = Math.random()
        }
      },
      // 删除
      removeEvent (row, rowIndex, type) {
        if (type === 'link') {
          this.$refs.linkTable.remove(row)
          this.inputForm.materialSupplierLinkDTOList.splice(rowIndex, 1)
        }
      },
      blurEmail (index) {
        if (this.commonJS.isNotEmpty(this.inputForm.materialSupplierLinkDTOList[index].email)) {
          if (!this.validateXG.isEmail(this.inputForm.materialSupplierLinkDTOList[index].email)) {
            this.$message.error('联系人信息中，第' + (index + 1) + '条数据的“邮箱”填写错误，请重新填写')
            this.inputForm.materialSupplierLinkDTOList[index].email = ''
            throw new Error('联系人信息中，第' + (index + 1) + '条数据的“邮箱”填写错误，请重新填写')
          }
        }
      },
      // 禁用编辑
      activeRowMethod ({ row, rowIndex }) {
        if (this.method === 'view') {
          return false
        }
        return true
      },
      rowStyle (event) {
        return 'cursor:pointer;'
      },
      async rowClick (event) {
        let id = this.gridData[event.rowIndex].companyid
        await this.enterpriseSearchService.enterpriseTicketInfo(id).then((data) => {
          this.inputForm.name = data.data.ENTNAME
          this.inputForm.uscCode = data.data.UNCID
          this.inputForm.address = data.data.OPLOC
          this.checkName()
        })
        this.visiblePop = false
      },
      async getPopTable () {
        let name = this.inputForm.name
        if (this.commonJS.isNotEmpty(name)) {
          await this.enterpriseSearchService.enterpriseSearchByName(name).then(({data}) => {
            this.gridData = data.data.items
            this.$refs.pops.updatePopper()
            this.popKey = Math.random()
          })
        }
        this.$refs.pops.updatePopper()
      },
      closePop () {
        this.visiblePop = false
      },
      checkName () {
        if (this.commonJS.isNotEmpty(this.inputForm.name)) {
          this.supplierService.findByName(this.inputForm.name).then(({data}) => {
            if (this.commonJS.isNotEmpty(data) && this.commonJS.isNotEmpty(data.name)) { // 说明有查询到这个名称的数据
              if ((this.commonJS.isNotEmpty(this.inputForm.id) && this.inputForm.id !== data.id) || this.commonJS.isEmpty(this.inputForm.id)) {
                this.$message.warning('供应商已存在')
              }
            }
          })
        }
      }
    }
  }
</script>

