<template>
  <div>
    <el-dialog
      title="送货地址"
      :visible.sync="dialogVisible"
      width="80%"
      :close-on-click-modal="false"
      :before-close="dialogBeforeClose"
      top="6vh"
    >
      <div class="common-page-content">
        <div style="display: flex; align-items: center" ref="contentPanel">
          <el-form
            ref="form"
            :model="searchForm"
            label-width="auto"
            label-position="right "
            :inline="true"
            type="flex"
            justify="left"
          >
            <el-form-item label="企业联系人">
              <el-input
                size="small"
                v-model="searchForm.enterpriseContact"
                clearable
                placeholder="请输入企业联系人"
              ></el-input>
            </el-form-item>
          </el-form>
          <div class="container-btn">
            <el-button
              size="small"
              icon="el-icon-search"
              type="danger"
              class="btn btn-plus"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button
              size="small"
              icon="el-icon-refresh-right"
              class="btn btn-plus"
              @click="clearSearchForm"
            >
              重置
            </el-button>
          </div>
        </div>
        <el-row class="common-table-container flex searchPanel">
          <el-col :span="24" class="common-table-wrapper">
            <div class="common-btn-group">
              <el-button
                size="small"
                icon="el-icon-plus"
                type="primary"
                class="btn btn-plus"
                @click="handleAdd"
              >
                新增
              </el-button>
              <el-button
                size="small"
                slot="reference"
                icon="el-icon-delete"
                type="danger"
                class="btn btn-delete"
                @click="handleDelete"
              >
                {{ this.$t('common.delete') }}
              </el-button>
            </div>
            <!-- LJ：表格高度自适应需配合样式  btn-pagenation 有按钮有分页  btngroup只有按钮  pagenation只有分页 -->
            <div class="common-table-content btn-pagenation">
              <el-table
                :border="true"
                stripe
                fit
                @selection-change="handleSelectionChange"
                height="100%"
                size="mini"
                v-loading="tableLoading"
                ref="multipleSelection"
                :data="tableData"
              >
                <el-table-column type="selection" min-width="5%" align="center">
                </el-table-column>
                <el-table-column
                  prop="enterpriseName"
                  show-overflow-tooltip
                  min-width="130px"
                  align="center"
                  label="企业名称"
                  resizable
                >
                </el-table-column>
                <el-table-column
                  prop="enterpriseContact"
                  show-overflow-tooltip
                  min-width="100px"
                  align="center"
                  label="企业联系人"
                  resizable
                >
                </el-table-column>
                <el-table-column
                  prop="enterpriseContactPhone"
                  show-overflow-tooltip
                  min-width="110px"
                  align="center"
                  label="企业联系电话"
                  resizable
                >
                </el-table-column>
                <el-table-column
                  prop="code"
                  show-overflow-tooltip
                  min-width="150px"
                  align="center"
                  label="送货地址编号"
                  resizable
                >
                </el-table-column>
                <el-table-column
                  prop="enterpriseContactAddress"
                  show-overflow-tooltip
                  min-width="150px"
                  align="center"
                  label="送货地址"
                  resizable
                >
                </el-table-column>
                <el-table-column
                  prop="defaultStatus"
                  show-overflow-tooltip
                  min-width="100px"
                  align="center"
                  label="是否默认"
                  resizable
                >
                  <template v-slot="{row}">
                    {{ getDictName('qyshdzmrzt', row.defaultStatus) }}
                  </template>
                </el-table-column>
                <el-table-column min-width="120px" align="center" label="操作">
                  <template v-slot="{row}">
                    <template>
                      <el-button
                        icon="el-icon-edit"
                        type="primary"
                        plain
                        size="small"
                        @click="handleEdit(row)"
                        >编辑</el-button
                      >
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="common-pagenation">
              <el-pagination
                ref="paginationPanel"
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="params.pageBean.page"
                :page-sizes="[20, 30, 40, 50]"
                :page-size="params.pageBean.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="params.pageBean.total"
              >
              </el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">应用</el-button>
        <el-button
          type="primary"
          style="width: 110px !important"
          @click="saveAll"
          >应用到所有物料</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="添加"
      :visible.sync="visible"
      width="50%"
      top="6vh"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <div class="form-content">
        <el-form
          ref="formInfo"
          :model="parameter"
          label-width="auto"
          label-position="right"
          :rules="rules"
          v-loading="loading"
        >
          <template>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="企业名称" prop="enterpriseName">
                  <el-input
                    v-model="parameter.enterpriseName"
                    clearable
                    placeholder="请输入企业名称"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="企业联系人" prop="enterpriseContact">
                  <el-input
                    clearable
                    v-model="parameter.enterpriseContact"
                    placeholder="请输入企业联系人"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item
                  label="企业联系电话"
                  prop="enterpriseContactPhone"
                >
                  <el-input
                    v-model="parameter.enterpriseContactPhone"
                    clearable
                    placeholder="请输入企业联系电话"
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="送货地址" prop="enterpriseContactAddress">
                  <el-input
                    v-model="parameter.enterpriseContactAddress"
                    clearable
                    placeholder="请输入企业送货地址"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="是否默认送货地址" prop="defaultStatus">
                  <dict-select
                    dictCode="qyshdzmrzt"
                    :hasDefaultOption="true"
                    v-model="parameter.defaultStatus"
                    style="width: 100%"
                    clearable
                    placeholder="请选择是否默认送货地址"
                  />
                </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>
    </el-dialog>
  </div>
</template>

<script>
import pagination from '@/components/pagination'
import {TableMixin} from '@/mixins/tableMixin'
import utils from '@/utils.js'
export default {
  components: {
    pagination,
  },
  mixins: [TableMixin],
  data() {
    return {
      dialogVisible: false,
      tableMaxHeight: 400,
      loading: false,
      tableLoading: false,
      tableData: [],
      multipleSelection: [],
      currentUser: {},
      visible: false,
      saveing: false,
      params: {
        pageBean: {
          page: 1,
          pageSize: 20,
          total: 0,
        },
        querys: [],
      },
      rules: {
        enterpriseContact: [
          {
            required: true,
            message: '请输入企业联系人',
            trigger: ['blur', 'change'],
          },
        ],
        enterpriseName: [
          {
            required: true,
            message: '请输入企业名称',
            trigger: ['blur', 'change'],
          },
        ],
        enterpriseContactAddress: [
          {
            required: true,
            message: '请输入企业送货地址',
            trigger: ['blur', 'change'],
          },
        ],
        defaultStatus: [
          {
            required: true,
            message: '请选择是否默认送货地址',
            trigger: ['blur', 'change'],
          },
        ],
      },
      parameter: {
        enablingStatus: 1,
        defaultStatus: 0,
      },
      searchForm: {
        enterpriseContact: '',
      }, // 顶部搜索对象
    }
  },
  created() {},
  methods: {
    open() {
      this.dialogVisible = true
      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.parameter.enterpriseContact = this.currentUser.user.fullname
      this.parameter.enterpriseContactPhone = this.currentUser.user.mobile
      this.loadData()
    },
    dialogBeforeClose() {
      this.dialogVisible = false
    },
    getDictName(code, value) {
      return utils.getDictName(code, value)
    },
    handleClose() {
      this.visible = false
      this.parameter = {
        enablingStatus: 1,
        defaultStatus: 0,
      }
      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.parameter.enterpriseContact = this.currentUser.user.fullname
      this.parameter.enterpriseContactPhone = this.currentUser.user.mobile
    },
    //获取数据
    loadData() {
      this.tableLoading = true
      this.$http
        .post('${portal}/bizDeliveryAddress/v1/queryByPageOrg', this.params)
        .then((res) => {
          this.tableLoading = false
          const data = (res && res.data) || {}
          this.tableData = data.rows || []
          this.params.pageBean.page = data.page
          this.params.pageBean.pageSize = data.pageSize
          this.params.pageBean.total = data.total
        })
    },
    //添加
    handleAdd() {
      this.visible = true
    },
    // 编辑
    handleEdit(rows) {
      this.parameter = rows
      this.visible = true
    },
    // 删除
    handleDelete() {
      let selection = this.$refs.multipleSelection.selection
      if (selection.length === 0) {
        this.$alert('请选择要删除的数据！', this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          type: 'warning',
        })
      } else {
        let ids = []
        selection.forEach((item) => {
          let str = item.id
          ids.push(str)
        })
        ids = ids.join(',')
        this.$confirm(this.$t('common.sureDelete'), this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning',
        }).then(() => {
          this.tableLoading = true
          this.$http
            .remove('${portal}/bizDeliveryAddress/v1/?ids=' + ids)
            .then((res) => {
              this.tableLoading = false
              if (res.data.state) {
                this.$message.success('删除成功！')
                this.handleSearch()
              }
            })
        })
      }
    },
    handleSelectionChange(val) {
            this.multipleSelection = val
            if (!this.multiple && this.multipleSelection.length > 1) {
                this.$refs.multipleSelection.toggleRowSelection(
                    this.multipleSelection[0],
                    false
                )
            }
        },
    handleSave() {
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          this.saveing = true
          this.parameter.defaultStatus = Number(this.parameter.defaultStatus)
          this.$http
            .post(
              '${portal}/bizDeliveryAddress/v1/saveOrUpdateEntity',
              this.parameter
            )
            .then((res) => {
              this.saveing = false
              this.loading = false
              if (res.data.state) {
                this.$message.success(res.data.message)
                this.handleClose()
                this.loadData()
              }
            })
        }
      })
    },
    //重置
    clearSearchForm() {
      this.searchForm = {
        enterpriseContact: '',
      }
      this.params.pageBean.page = 1
      this.handleSearch()
    },
    // 顶部搜索
    handleSearch() {
      let obj = this.searchForm
      let querys = []
      for (let i in obj) {
        if (obj[i]) {
          querys.push({
            group: 'main',
            operation:
              i == 'enterpriseContact' || i == 'supplier_name_'
                ? 'LIKE'
                : 'EQUAL',
            parentGroup: '',
            property: i,
            relation: 'AND',
            value: obj[i],
          })
        }
      }
      this.params.querys = querys
      this.params.pageBean.page = 1
      this.loadData()
    },
    handleCurrentChange(page) {
      this.params.pageBean = {...this.params.pageBean, page}
      this.loadData(this.params)
    },
    handleSizeChange(pageSize) {
      this.params.pageBean = {...this.params.pageBean, pageSize}
      this.loadData(this.params)
    },
    save(){
      let list = []
      list = this.multipleSelection
      list.forEach(item=>{
        this.$set(item,'sort',1)
      })
      this.$emit('emit',list)
      this.dialogBeforeClose()
    },
    saveAll(){
      let list =[]
      list = this.multipleSelection
      list.forEach(item=>{
        this.$set(item,'sort',2)
      })
      this.$emit('emit',list)
      this.dialogBeforeClose()
    }
  },
}
</script>

<style lang="scss" scoped>
/deep/.el-dialog__body {
  height: 570px;
}
.common-table-container {
  height: 100%;
}
</style>