<!--
 * @Description: 查看/编辑/新增协议弹框
 * @Author: dijia
 * @Date: 2021-06-15 09:32:19
-->
<template>
  <div>
    <!-- 新增的dialog -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="1135px"
      custom-class="shop_mall_dialog"
    >
      <el-form
        ref="protocolFormRef"
        :rules="rules"
        :model="protocolForm"
        :inline-message="true"
        style="padding:10px"
      >
        <p class="page-titles mb10">
          1.协议基本信息
        </p>
        <table class="from_table_base mb10">
          <tr>
            <td><el-form-item label="协议名称" prop="protocolName" /></td>
            <td>
              <gx-input
                v-model.trim="protocolForm.protocolName"
                type="text"
                placeholder="请输入协议名称"
                :disabled="protocolType==='view'"
              />
            </td>
            <td><el-form-item label="开始时间" prop="startTime" /></td>
            <td>
              <el-date-picker
                v-model="protocolForm.startTime"
                type="datetime"
                placeholder="请选择开始时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                :disabled="protocolType==='view'"
              />
            </td>
          </tr>
          <tr>
            <td><el-form-item label="协议内容" prop="remark" /></td>
            <td>
              <gx-input
                v-model.trim="protocolForm.remark"
                type="text"
                placeholder="请输入协议内容"
                :disabled="protocolType==='view'"
              />
            </td>
            <td><el-form-item label="终止时间" prop="endTime" /></td>
            <td>
              <el-date-picker
                v-model="protocolForm.endTime"
                type="datetime"
                placeholder="请选择终止时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                :disabled="protocolType==='view'"
              />
            </td>
          </tr>
        </table>
        <p class="page-titles mb10">
          2.协议扩展内容
        </p>
        <el-button v-if="protocolType!=='view'" class="mb10 flex_btn" type="purple" @click="addRow">
          添加分类
        </el-button>
        <div v-for="(item, index) in protocolForm.supplierQueryDtoList" :key="item.categoryId" class="mb16 box-container">
          <div class="table_flex">
            <table class="form_table">
              <tr>
                <td>
                  <el-form-item
                    label="商品类别："
                    :prop="`supplierQueryDtoList.${index}.categoryName`"
                    :rules="rules.categoryName"
                  />
                </td>
                <td>
                  <el-input
                    v-model="item.categoryName"
                    disabled
                    :title="item.categoryName"
                    class="categoryInfoOverflow"
                  />
                </td>
              </tr>
            </table>
            <el-button
              v-if="protocolType!=='view'"
              size="small"
              class="mt_6"
              @click="showSelectCategory(index)"
            >
              选择分类
            </el-button>
            <span class="pur-name">
              供应商名称：
            </span>
            <table class="form_table_list mt_6">
              <tr v-for="(val, ind) in item.supplierDtoList" :key="val.supplierId">
                <td>
                  <el-form-item
                    :prop="`supplierQueryDtoList.${index}.supplierDtoList.${ind}.supplierId`"
                    :rules="rules.supplierId"
                  />
                </td>
                <td :title="val.supplierName" class="cursor">
                  {{ val.supplierName }}
                </td>
                <td v-if="protocolType!=='view'">
                  <el-button type="primary" plain size="mini" @click="showSelectPurchaser(index, ind)">
                    选择
                  </el-button>
                  <el-button type="danger" plain size="mini" @click="deletePurchaser(index, val, ind)">
                    删除
                  </el-button>
                </td>
              </tr>
            </table>
            <el-button
              v-if="protocolType!=='view'"
              type="purple"
              class="mt_6"
              @click="addPurchaser(index)"
            >
              添加
            </el-button>
            <el-button
              v-if="protocolType!=='view'"
              type="purple"
              class="purchaser_flex mt_6"
              style="align-self: flex-start;"
              @click="removeAll(index)"
            >
              删除供应商
            </el-button>
          </div>
        </div>
      </el-form>
      <span
        v-if="protocolType!=='view'"
        slot="footer"
        class="dialog-footer"
      >
        <el-button type="purple" style="margin-right:50px" @click="addProtocol()">保 存</el-button>
        <el-button @click="clickReturn">返 回</el-button>
      </span>
    </el-dialog>
    <!-- 选择供货商品类别的dialog -->
    <el-dialog
      v-if="selectVisible"
      :visible.sync="selectVisible"
      :before-close="handleCloseSelect"
      append-to-body
      title="请选择分类"
      width="40%"
      custom-class="shop_mall_dialog"
    >
      <!-- tree -->
      <el-row>
        <el-col :offset="3" :span="18">
          <!-- 搜索条件 -->
          <el-input v-model="filterText" class="mb10" placeholder="输入关键字进行过滤" clearable />
          <el-scrollbar style="height:400px">
            <el-tree
              ref="categoryTree"
              :props="defaultProps"
              :data="categoryData"
              :default-checked-keys="defaultCheckedKeys"
              :check-strictly="true"
              node-key="id"
              show-checkbox
              default-expand-all
              :filter-node-method="filterNode"
              @check-change="handleCheckChange"
              @check="handleCurrentChange"
            />
          </el-scrollbar>
        </el-col>
      </el-row>
      <!-- footer -->
      <span slot="footer" class="dialog-footer">
        <el-button type="purple" style="margin-right:50px" @click="addToForm">
          确 定
        </el-button>
        <el-button @click="cancelSelect">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 选择供应商的dialog -->
    <el-dialog
      :visible.sync="purchaserVisible"
      :before-close="handleClosePurchaser"
      append-to-body
      title="请选择供应商"
      width="40%"
      custom-class="shop_mall_dialog"
    >
      <div class="purchaser-nav">
        <div class="purchaser-left">
          <p>
            <span>供应商名称：</span>
            <el-input
              v-model.trim="departRole.departName"
              style="width:60%;"
              placeholder=""
            />
          </p>
        </div>
        <div class="purchaser-right">
          <el-button type="purple" @click="onSearch">
            查询
          </el-button>
          <el-button type="gray" @click="resetRole">
            重置
          </el-button>
        </div>
      </div>
      <section style="padding:0 25px;">
        <el-table
          ref="purchaserTable"
          :data="purchaserData"
          highlight-current-row
          style="width: 100%;"
          max-height="230"
          @current-change="tableCurrentChange"
        >
          <el-table-column
            prop="departName"
            label="供应商名称"
            align="left"
          />
          <el-table-column
            prop="address"
            label="地址"
            align="left"
          />
          <el-table-column
            prop="linktel"
            label="联系方式"
            align="left"
          />
        </el-table>
      </section>
      <div class="dialog-pagination shopmall-pagination p16">
        <div class="page-number">
          共{{ Math.ceil(total /departRole.pageSize) }}页
          {{ total }}条
        </div>
        <el-pagination
          small
          :current-page="departRole.pageNo"
          :total="total"
          :page-sizes="[10,20,50]"
          :pager-count="5"
          class="pagination-width"
          background
          layout="prev, pager, next, sizes"
          @current-change="pickHandle"
          @size-change="handleSizeChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="purple" style="margin-right:50px" @click="saveSelect">确 定</el-button>
        <el-button @click="cancelTable">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// api
import {
  doAddOrUpdateProtocol,
  getGoodsclassTree,
  getOrganizationList,
  checkSupplierExist,
  saveSupplier
} from '@/api/shoppingmall/products'
/* 常用方法 */
import { characters1_auto } from '@/assets/js/validate'
/* 公用方法*/
import { filterObj } from '@/assets/js/utils'// 常用方法
export default {
  name: 'ProtocolNnterDialog',
  props: {
  },
  data() {
    return {
      // tree
      filterText: '',
      // 新增的form表单
      protocolForm: {},
      // protocolForm 检验规则
      rules: {
        protocolName: [
          { required: true, validator: characters1_auto, trigger: 'blur' }
        ],
        remark: [
          { required: true, validator: characters1_auto, trigger: 'blur' }
        ],
        startTime: [
          { required: true, validator: characters1_auto, trigger: 'blur' }
        ],
        endTime: [
          { required: true, validator: characters1_auto, trigger: 'blur' }
        ],
        categoryName: [
          { required: true, validator: characters1_auto, trigger: 'blur' }
        ],
        supplierId: [
          { required: true, validator: characters1_auto, trigger: 'blur' }
        ]
      },
      // 选择供应商的dialog
      purchaserVisible: false,
      // 选择供货商品类别的dialog
      selectVisible: false,
      // 供应商表格数据
      purchaserSelectData: [],
      // 供应商表格数据
      purchaserData: [],
      // 分类数据
      categoryData: [],
      // tree配置选项
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 查询供应商的input字段
      purchaserName: '',
      // 选择供应商params
      departRole: {
        pageNo: 1,
        pageSize: 10,
        departRoleName: 12,
        departName: ''
      },
      total: 0,
      // tree默认选中的节点
      defaultCheckedKeys: [],
      // 选中的供应商
      selectRows: [],
      // 供应商table所在index
      sindex: null,
      // 供应商整体index
      ssindex: null,
      // 分类信息对象
      categoryInfo: {},
      // 弹框显示
      dialogVisible: false,
      // 操作类型 add 新增/view 查看/edit 编辑
      protocolType: 'add',
      // 弹框标题
      dialogTitle: '',
      // 点击的第几个供应商的选择分类的index
      selectCategory: 0
    }
  },
  computed: {
  },
  watch: {
    // 监听新增dialog的显示状态
    'dialogVisible'(val) {
      if (!val) {
        this.resetForm()
      }
    },
    filterText(val) {
      this.$refs.categoryTree.filter(val)
    },
    selectVisible(val) {
      if (!val) {
        this.filterText = ''
      }
    },
    'purchaserVisible'(val) {
      if (!val) {
        this.departRole.departName = ''
      }
    }
  },
  methods: {
    // 打开弹框
    open(dialogData) {
      this.dialogVisible = dialogData.visible
      this.protocolType = dialogData.type // 操作类型 add 新增/view 查看/edit 编辑
      if (this.protocolType === 'add') { // 新增
        this.dialogTitle = '新增协议'
        this.protocolForm = {
          protocolName: null, // 协议名称
          remark: null, // 协议详情
          startTime: null, // 开始时间
          endTime: null, // 结束时间
          // 协议扩展信息对象
          supplierQueryDtoList: [
            {
              categoryId: null, // 分类ID
              categoryName: null, // 分类名称
              supplierDtoList: [{
                supplierId: null, // 供应商ID
                supplierName: null // 供应商名称
              }]
            }
          ]
        }
        // 获取分类json树 供应商列表
        this.getInfo()
      } else if (this.protocolType === 'view') { // 查看
        this.dialogTitle = '查看协议'
        this.protocolForm = JSON.parse(JSON.stringify(dialogData.advertData))
      } else { // 编辑
        this.dialogTitle = '编辑协议'
        this.protocolForm = JSON.parse(JSON.stringify(dialogData.advertData))
        // 获取分类json树 供应商列表
        this.getInfo()
      }
    },
    // 获取分类json树 供应商列表
    getInfo() {
      // 获取分类json树
      this.getCategoryTree()
      // 获取供应商列表
      this.getOrganization()
    },
    // 关闭选择商品类别dialog时的回调
    handleCloseSelect() {
      this.selectVisible = false
      // do something
    },
    // 关闭选择供应商dialog时的回调
    handleClosePurchaser() {
      this.purchaserVisible = false
      // do something
    },
    // 新增/编辑协议
    addProtocol() {
      this.$refs.protocolFormRef.validate((valid) => {
        if (!valid) return
        const message = this.dialogTitle + '成功！'
        const len = this.protocolForm.supplierQueryDtoList.length
        const flag = this.protocolForm.supplierQueryDtoList.filter(item => item.supplierDtoList.length === 0).length
        if (!len) { // 如果供应商整体length为0
          this.$message({
            type: 'warning',
            message: '请添加供应商！！'
          })
          return
        }
        if (flag) { // 如果供应商未选择
          this.$message({
            type: 'warning',
            message: '请选择至少一家供应商！'
          })
          return
        }
        doAddOrUpdateProtocol(this.protocolForm).then((res) => {
          if (res.header.ret === '0') {
            this.$message({
              message: message,
              type: 'success'
            })
            // 通知父组件刷新list
            this.$emit('callback')
            // 关闭新增的dialog
            this.dialogVisible = false
          }
        })
      })
    },
    // 获取选中的商品分类数据
    handleCurrentChange(data) {
      // 此函数 当复选框被点击的时候触发 无法判断是否选中  只能知道选中的节点
      // this.categoryInfo = { id: data.id, name: data.name }
    },
    // 将选中的tree节点添加到表单
    addToForm() {
      // 查找是否已添加此分类
      // 注意新供应商的分类为null 添加时，若未选中分类节点 就会变为 undefined  判断选中节点是否存在，来避免未选节点时不能按确定的情况
      const hasId = this.protocolForm.supplierQueryDtoList.filter(item => (item.categoryId === this.categoryInfo.id) && this.categoryInfo.id)
      if (hasId.length) {
        this.$message({
          type: 'warning',
          message: '已选择此分类！请选择其他分类！'
        })
        return
      }
      // 获取选择的节点 为了处理回显后直接确定 选中的节点为空的情况
      this.categoryInfo = this.$refs.categoryTree.getCheckedNodes()[0] || {}
      // 将选中的 node 添加到 protocolForm
      this.protocolForm.supplierQueryDtoList[this.selectCategory].categoryId = this.categoryInfo.id
      this.protocolForm.supplierQueryDtoList[this.selectCategory].categoryName = this.categoryInfo.name
      this.selectVisible = false
    },
    // 节点选中状态发生变化时的回调 节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点
    handleCheckChange(data, checked, node) {
      // 节点被选中时
      if (checked) {
        // 点击categoryTree复选框触发,只能单选
        this.$refs.categoryTree.setCheckedNodes([data])
        this.categoryInfo = JSON.parse(JSON.stringify(data))
      }
    },
    // 选择表格数据
    tableCurrentChange(val) {
      this.selectRows = val
    },
    // 获取商品分类json树
    getCategoryTree(pid) {
      getGoodsclassTree(pid).then((res) => {
        if (res.header.ret === '0') {
          this.categoryData = res.data
        }
      })
    },
    // 获取供货商列表
    getOrganization() {
      const params = this.getQueryParams()// 查询条件
      getOrganizationList(params).then((res) => {
        if (res.header.ret === '0') {
          this.purchaserData = res.data.records
          this.total = res.data.total
        }
      })
    },
    // 查询条件
    getQueryParams() {
      const param = Object.assign({}, this.departRole)
      // param.pageNo = this.departRole.pageNo
      // param.pageSize = this.departRole.pageSize
      return filterObj(param)
    },
    // 搜索
    onSearch() {
      this.departRole.pageNo = 1
      this.departRole.pageSize = 10
      // 获取列表信息
      this.getOrganization()
    },
    resetRole() {
      this.departRole.departName = ''
      this.departRole.pageNo = 1
      this.departRole.pageSize = 10
      this.getOrganization()
    },
    // 显示选择分类dialog
    showSelectCategory(index) {
      this.selectCategory = index
      // 打开的第几个供应商的选择分类的index
      this.defaultCheckedKeys.length = 0
      this.defaultCheckedKeys.push(this.protocolForm.supplierQueryDtoList[index].categoryId)
      // 打开时清空已选择的分类对象
      this.categoryInfo = {}
      // 显示dialog
      this.selectVisible = true
    },
    // 显示供应商dialog
    showSelectPurchaser(index, sindex) {
      this.ssindex = index
      this.sindex = sindex
      this.purchaserVisible = true
    },
    // 选择商品分类dialog,点击取消
    cancelSelect() {
      this.selectVisible = false
    },
    // 删除供应商整体
    removeAll(index) {
      if (this.protocolForm.supplierQueryDtoList.length === 1) {
        this.$notify({
          showClose: false,
          title: '提醒',
          message: '不可删除！应至少有一家供应商！',
          type: 'warning'
        })
        return
      }
      this.protocolForm.supplierQueryDtoList.splice(index, 1)
    },
    // 重置表单
    resetForm() {
      this.defaultCheckedKeys.length = 0
      this.$refs.protocolFormRef.resetFields()
      this.$refs.protocolFormRef.clearValidate()
      // 重置新增协议对象
      this.protocolForm.supplierQueryDtoList = [
        {
          categoryId: null, // 分类ID
          categoryName: null, // 分类名称
          supplierDtoList: [{
            supplierId: null, // 供应商ID
            supplierName: null // 供应商名称
          }]
        }
      ]
    },
    // 点击返回
    clickReturn() {
      this.dialogVisible = false
    },
    // pageNo变化
    pickHandle(val) {
      this.departRole.pageNo = val
      this.getOrganization()
    },
    // 分页size变化
    handleSizeChange(val) {
      this.departRole.pageNo = 1
      this.departRole.pageSize = val
      this.getOrganization()
    },
    // 增加一行空的供应商
    addRow() {
      this.protocolForm.supplierQueryDtoList.push({
        categoryId: null, // 分类ID
        categoryName: null, // 分类名称
        supplierDtoList: [{
          supplierId: null, // 供应商ID
          supplierName: null // 供应商名称
        }]
      })
    },
    // 点击返回
    cancelTable() {
      this.purchaserVisible = false
    },
    // 按确定添加供应商
    addPurchaser(index) {
      this.protocolForm.supplierQueryDtoList[index].supplierDtoList.push({
        supplierId: null, // 供应商ID
        supplierName: null // 供应商名称
      })
    },
    // 删除选中的供应商
    deletePurchaser(index, row, selectIndex) {
      if (this.protocolForm.supplierQueryDtoList[index].supplierDtoList.length === 1) {
        this.$notify({
          showClose: false,
          title: '提醒',
          message: '不可删除！请选择至少一家供应商！',
          type: 'warning'
        })
        return
      }
      this.protocolForm.supplierQueryDtoList[index].supplierDtoList.splice(selectIndex, 1)
    },
    // 保存选择的供应商
    saveSelect() {
      // 查询供应商是否已经同步到电子超市
      if (this.selectRows.departId) {
        checkSupplierExist(this.selectRows.departId).then(res => {
          // res.data 为 boolean值,未同步
          if (!res.data) {
            this.$confirm('当前供应商未同步到电子超市，是否同步？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              confirmButtonClass: 'confirmBtn',
              cancelButtonClass: 'cancelBtn',
              type: 'warning'
            }).then(() => {
              const params = JSON.parse(JSON.stringify(this.selectRows))
              // 将供应商信息同步到电子超市
              saveSupplier(params).then(response => {
                if (response.data) {
                  this.$message.success('同步供应商成功！')
                  // 同步成功后,将供应商添加到 protocolForm
                  this.addSupplier()
                }
              }).catch(err => {
                throw new Error('同步供应商失败' + err)
              })
            }).catch(() => {
              return
            })
          } else {
            // 供应商已同步
            this.addSupplier()
          }
        })
      }
    },
    // 将供应商添加到 protocolForm
    addSupplier() {
      // 根据ID判断是否已添加到 protocolForm
      const hasLen = this.protocolForm.supplierQueryDtoList[this.ssindex].supplierDtoList.filter(item => item.supplierId === this.selectRows.departId).length
      if (hasLen) {
        this.$message({
          type: 'warning',
          message: '已添加此供应商！请添加其他供应商！'
        })
        return
      }
      this.$set(this.protocolForm.supplierQueryDtoList[this.ssindex].supplierDtoList[this.sindex], 'supplierId', this.selectRows.departId)
      this.$set(this.protocolForm.supplierQueryDtoList[this.ssindex].supplierDtoList[this.sindex], 'supplierName', this.selectRows.departName)
      this.purchaserVisible = false
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    }
  }
}
</script>

<style lang="less" scoped>
.purchaser_flex {
  display: flex;
  align-items: center;
}

.purchaser-nav {
  width: 100%;
  height: 60px;
  padding: 0 25px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .purchaser-left {
    display: flex;
    width: 60%;
    align-items: center;
    p {
      // width: 33%;
      display: flex;
      align-items: center;
      span {
        width: 40%;
      }
    }
  }
  .purchaser-right {
    display: flex;
    width: 30%;
    justify-content: space-around;
  }
}
.categoryInfoOverflow {
  /deep/.el-input__inner {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.page-titles {
    font-family: PingFangSC-Regular, "PingFang SC";
    font-weight: 400;
    font-style: normal;
    font-size: 16px;
}
.pagination-width {
  max-width: 360px;
}
.dialog-pagination {
  display: flex;
  justify-content: space-between;
}
.form_table {
  width: 30%;
  margin-right: 5px;
  td {
    line-height: 20px;
    padding: 6px;

    .el-form-item--small.el-form-item {
      margin: 0;
    }

    .el-input {
      width: 95%;
    }
  }

  >tr td:nth-child(1) {
    border: 1px solid #E0E0E0;
    background-color: #F5F7F9;
    width: 38%;
    /deep/.el-form-item .el-form-item__content .el-form-item__error {
      left: 113px;
      z-index: 1;
      position: absolute;
      width: 50px;
      top: 8px;
      user-select: none;
    }
  }

  >tr td:nth-child(2) {
    border: 1px solid #E0E0E0;
    width: 60%;
  }

}
.pur-name {
    border: 1px solid #E0E0E0;
    background-color: #F5F7F9;
    align-self: flex-start;
    margin-left: 5%;
    height: 44px;
    line-height: 44px;
    width: 10%;
    text-align: center;
}
// 只显示叶子节点的复选框
/deep/.el-tree-node{
    .is-leaf + .el-checkbox .el-checkbox__inner{
        display: inline-block;
    }
    .el-checkbox .el-checkbox__inner{
        display: none;
    }
}
/deep/.el-tree-node.is-current > .el-tree-node__content {
  color: #606266;
}
.form_table_list {
  width: 40%;
  margin-right: 20px;
  td {
    line-height: 20px;
    padding: 6px;
    border: 1px solid #E0E0E0;
    .el-form-item--small .el-form-item {
      margin: 0;
    }
    /deep/.el-form-item--small .el-form-item__content {
      line-height: 20px;
    }

    .el-input {
      width: 90%;
    }
  }

  >tr td:nth-child(1) {
    width: 5%;
    border: 0;
    padding: 6px 0;
    /deep/.el-form-item .el-form-item__content .el-form-item__error {
      left: 40px;
      position: absolute;
      width: 50px;
      user-select: none;
    }
  }

  >tr td:nth-child(2) {
    width: 35%;
    padding-left: 8px;
  }

  >tr td:nth-child(3) {
    text-align: center;
    width: 16%;
  }

}
.table_flex {
  width: 100%;
  display:flex;
  align-items:flex-start;
}
.from_table_base {
  width: 100%;

  td {
    border: 1px solid #E0E0E0;
    line-height: 20px;
    padding: 6px;

    .el-form-item--small.el-form-item {
      margin: 0;
    }

    .el-input,.inline {
      width: 90%;
    }
    .el-date-editor.el-input {
      width: 90%;
    }
  }

  >tr td:nth-child(odd) {
    background-color: #F5F7F9;
    width: 16%;
  }

  >tr td:nth-child(even) {
    width: 34%;
  }
}
.mt_6 {
  margin-top: 6px;
}
.box-container {
  padding: 5px;
  border: 1px solid #E0E0E0;
  border-radius: 5px;
  box-shadow: -1px -1px #e0e0e0;
}
/deep/.el-scrollbar__bar {
  opacity: 1;
}
</style>
