/*
 * @Author: kaka
 * @Date: 2018-09-03 11:29:07
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2019-04-26 14:10:09
 */

// 单据才有bill_status状态，主档只有一个usable是否启用
import ToolClass from '@utils/toolClass'
import Base from '@basicClass/base'
import billUtil from './bill_util'
// 单表uc
const utilUc = {
  props: ['is_innner_dialog'],
  mixins: [Base, billUtil],
  data() {
    return {
      direct_delete: false, // 是否直接删除
      is_restful: false,
      module_name: '', // 模块名
      api_query_list: '', // 查询列表
      api_save_one: '', // 新增或者修改
      api_delete_list: '', // 批量删除
      api_query_one: '', // 查询单条明细
      bill_query_one_detail: {},
      bill_query_one_copy: {}, // 用于对比数据
      page_sizes: this.$appConfig.pagination_page_sizes, // 分页
      page: 1,
      per_page: 10,
      total: 0,
      bill_list: [], // 列表
      searchParam: {}, // 搜索条件
      targetRow: {}, // 选中的行
      bill_detail_add_dialog: false,
      bill_search_popover_visible: false,
      formLabelWidth: '120px',
      menu_list: [], // 左侧菜单列表
      index_module_name: '', // 左侧主模块名
      index_api_query_list: 'query_list', // 查询菜单
      index_api_save_one: 'save_one', // 新增或者修改
      index_api_delete_one: 'delete_one', // 删除菜单
      index_api_query_one: 'query_one', // 查询单条菜单明细
      menu_dialog_add: false, // 左侧菜单新增
      menu_dialog_edit: false, // 左侧菜单修改
      menu_dialog_edit_add_title: '新增',
      ment_tree_ref: 'treeRef',
      menu_row: {},
      menu_row_detail_data: {},
      menu_height: '', // 左侧栏对高度
      bill_height: '', // 右侧主体的高度
      bill_not_check: {},
      index_data_id: 'id',
      index_data_back_id: 'id', // 树形菜单的主键
      bill_save_must_prop: {
        // 保存或者新增的时候的必填字段校验
      },
      bill_add_edit_dialg_form_list: [],
      selectedOptions: [],
      bill_status_judge: {}, // 审批流按钮
      page_reset: false, // 是否重置page
      Primary_unit: '', // 主单位，判断是否可以删除
      bill_the_type: 'document_type', // 单据类型 默认是单据类
      menu_type: '', // 菜单类型
      Global_data_select: [],
      row_detail_id: 'id',
      pagination: true, // 是否分页
      menu_search_parm: {},
      query_bill_route_parm: {},
      provider_id: ''
    }
  },
  computed: {
    bill_status0() {
      return !this.filter_status('0')
    }
  },
  watch: {
    searchParam: {
      handler() {
        // 解决搜索条件改变后 分页搜索的bug(ps:后端应该也可以解决,姑且在前端处理)
        this.page_reset = true
      },
      deep: true
    }
  },
  mounted() {
    const that = this
    window.onresize = function() {
      that.$nextTick(() => {
        that.set_table_style()
      })
    }
    this.$nextTick(() => {
      this.set_table_style()
    })
  },
  activated() {
  },
  methods: {
    /**
     * 在active中调用;
     * 没有左侧栏的情况一定不要重定义index_module_name
     * 左侧栏 没有请求的时候 一定不要重定义index_module_name
     */
    init_query(falge = false) {
      if (falge) {
        // 左右两边同时进行
        this.get_menu_list(false)
        this.query_bill_list()
      } else {
        // 要等左侧栏请求完再请求右边list
        if (this.index_module_name) {
          this.get_menu_list()
        } else {
          this.query_bill_list()
        }
      }
    },
    delete_one(id) {
      this.base_delete_one(id).then(() => {
        // 删除后的处理逻辑
      })
    },
    delete_list(ids) {
      const parm = { ids_list: ids }
      this.base_delete_list(parm).then(() => {
        // 删除后的处理逻辑
      })
    },
    query_bill_list_before() {},
    query_bill_list_callback(data) {},
    /**
     * 单据列表
     * @param {*} id
     */
    query_bill_list() {
      const me_id = this.provider_id
      if (this.page_reset) {
        this.page = 1
        this.page_reset = false
      }
      // 问号参数
      let parm2 = {}
      if (this.pagination) {
        parm2 = {
          page: this.page,
          per_page: this.per_page
        }
      }
      this.query_bill_list_before()
      // 删除一些不合格的查询条件
      for (const key in this.searchParam) {
        const r = this.searchParam[key]
        const r_list = [null, 'null', undefined, 'undefined']
        if (r_list.includes(r)) delete this.searchParam[key]
      }
      let p = {}
      if (this.searc_obj) {
        p = Object.assign(parm2, this.searchParam, this.searc_obj) // 做为问号参数
      } else {
        p = Object.assign(parm2, this.searchParam) // 做为问号参数
      }
      if (this.is_restful) {
        this.api_query_list = ''
      }
      this.$API
        .get(`${this.module_name}/${this.api_query_list}/`, this.query_bill_route_parm, p)
        .then(res => {
          this.query_bill_list_callback(res.data.table)
          if (this.pagination) {
            if (this.provider_id) {
              res.data.table.map((item, index) => {
                if (this.module_name === '/mesAPI/pu_order') {
                  if (item.provider_id === me_id && this.provider_id === me_id) {
                    res.data.table[index].me_order = true
                  } else {
                    res.data.table[index].me_order = false
                  }
                } else {
                  if (item.customer_id === me_id && this.provider_id === me_id) {
                    res.data.table[index].me_order = true
                  } else {
                    res.data.table[index].me_order = false
                  }
                }
              })
            }
            this.bill_list = res.data.table
            this.total = res.data.paging.total - 0
            this.page = res.data.paging.page - 0
            this.per_page = res.data.paging.per_page - 0
          } else {
            this.bill_list = res.data.table
          }
          this.bill_search_popover_visible = false
        })
    },
    // 详情获取后的判断逻辑
    bill_query_one_after(data) {},
    bill_query_one(id) {
      const that = this
      this.$nextTick(function() {
        for (const item of this.bill_add_edit_dialg_form_list) {
          that.$refs[item].resetFields()
        }
      })
      this.bill_query_one_detail = {}
      this.bill_query_one_copy = {}
      const routerParms = {
        routerUrl: 'id',
        data: {
          id: id
        }
      }
      if (this.is_restful) {
        this.api_query_one = ''
      }
      this.$API
        .get(`${this.module_name}/${this.api_query_one}/`, routerParms)
        .then(res => {
          this.bill_query_one_detail = res.data
          this.bill_query_one_after(this.bill_query_one_detail)
          this.bill_query_one_copy = ToolClass.copy_object(
            this.bill_query_one_detail
          )
          this.$refs.multipleTable.clearSelection()
          this.$refs.multipleTable.setCurrentRow(
            this.bill_list[this.targetIndex]
          )
          this.$refs.multipleTable.toggleRowSelection(
            this.bill_list[this.targetIndex]
          )
        })
    },
    bill_save_one_before() {},
    /**
     *
     * @param {*} flage  // 1 新增 2 修改
     */
    bill_save_one(flage) {
      this.bill_save_one_before()
      var that = this
      let data = {}
      if (flage === 1) {
        data = this.bill_query_one_detail
      } else {
        // 修改
        data = ToolClass.filter_change_data(
          this.bill_query_one_copy,
          this.bill_query_one_detail,
          this.bill_not_check
        )
        console.log(data)
      }
      for (const prop in data) {
        if (!data[prop] && Reflect.has(this.bill_save_must_prop, prop)) {
          this.$message(this.bill_save_must_prop[prop])
          return
        }
      }
      // 判定是否有改动
      if (
        flage === 2 &&
        Object.keys(data).length <= Object.keys(this.bill_not_check).length
      ) {
        this.$message('数据未改动！')
        return
      }
      if (this.is_restful) {
        this.api_save_one = ''
      }
      this.$API
        .post(`${this.module_name}/${this.api_save_one}/`, {}, {}, data)
        .then(res => {
          if (flage === 1) {
            // 新增 再查询一次
            this.query_bill_list()
          } else {
            // 修改 把返回值重新设置当前修改行
            if (res.data) {
              this.$set(this.bill_list, this.targetIndex, res.data)
              this.$refs.multipleTable.toggleRowSelection(
                this.bill_list[this.targetIndex]
              )
            } else {
              this.query_bill_list()
            }
          }
          this.$nextTick(function() {
            for (const item of this.bill_add_edit_dialg_form_list) {
              that.$refs[item].resetFields()
            }
          })
          this.bill_detail_add_dialog = false
        })
    },
    bill_save_one_after() {},
    /**
     *
     * @param {*} flage// 用来判断是否是保存并新增
     */
    bill_save_one_n(flage) {
      this.$refs.form_detail.validate(valid => {
        if (valid) {
          const data = ToolClass.filter_change_data(
            this.bill_query_one_copy,
            this.bill_query_one_detail,
            this.bill_not_check
          )
          if (this.is_restful) {
            this.api_save_one = ''
          }
          this.$API
            .post(`${this.module_name}/${this.api_save_one}/`, {}, {}, data)
            .then(res => {
              // this.init_query()
              if (!data.id) {
                this.init_query()
              }
              if (flage) {
                // 保存并新增
                // 删除一些字段
                Object.keys(this.bill_query_one_detail).forEach(prop => {
                  if (!Reflect.has(this.reserve_prop, prop)) {
                    delete this.bill_query_one_detail[prop]
                  }
                })
                this.bill_query_one_copy = {}
              } else {
                // 仅仅修改
                this.bill_detail_add_dialog = false
                // 修改 把返回值重新设置当前修改行
                this.$set(this.bill_list, this.targetIndex, res.data)
                this.$refs.multipleTable.toggleRowSelection(
                  this.bill_list[this.targetIndex]
                )
              }
              this.bill_save_one_after(flage)
            })
        }
      })
    },
    /**
     * 批量删除
     */
    bill_delete_list_before() {},
    bill_delete_list_after() {},
    bill_delete_list() {
      let me_order = true
      let bill_status = true
      let is_system = true
      const list = this.$refs.multipleTable.selection
      if (!list.length) {
        this.$message('请选中菜单项')
        return
      }
      list.map((item) => {
        if (item.bill_status !== '0') {
          bill_status = false
        }
        if (item.is_system) {
          is_system = false
        }
        if (item.me_order) {
          me_order = false
        }
      })
      if (!bill_status) {
        this.$message(`已选中的数据下有已发送或已完结状态，不可以删除`)
        return
      }
      if (!is_system) {
        this.$message(`已选中的数据下有系统订单，不可以删除`)
        return
      }
      if (!me_order && this.module_name === '/mesAPI/pu_order') {
        this.$message(`已选中的数据下有供应商为本公司的采购单，不可以删除`)
        return
      }
      if (!me_order && this.module_name === '/mesAPI/im_shipment') {
        this.$message(`已选中的数据下有客户为本公司的出貨单，不可以删除`)
        return
      }
      this.bill_delete_list_before()
      const list_w = list.reduce((prov, next) => {
        prov.push(next.id)
        return prov
      }, [])
      if (this.bill_the_type === 'master_type') {
        let status = true
        // 主档类型
        list.map((item, index) => {
          if (item.isdelete) {
            if (status) {
              status = false
              this.$message(`已选中的数据下有被${item.quote}引用，不可以删除`)
            }
            return
          }
          if (
            item[this.Primary_unit] &&
            this.bill_list.length > 1 &&
            list.length !== this.bill_list.length
          ) {
            if (status) {
              status = false
              this.$message(
                `已选中的数据下包含${this.main}，不可以删除, 请重置${this.main}`
              )
            }
            return
          }
        })
        if (status) {
          this.$confirm(`确定删除${list_w.length}条数据?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (!this.direct_delete) {
              this.before_delete_hint(list_w)
            } else {
              this.go_delete(list_w)
            }
          })
        }
      } else if (this.bill_the_type === 'document_type') {
        const ids = []
        let idsNot = 0 // 记录选中草稿的个数
        for (const item of list) {
          if (
            item.bill_status === '0' ||
            item.bill_status === '1' ||
            !item.bill_status
          ) {
            ids.push(item.id)
          } else {
            idsNot++
          }
        }
        if (!ids.length) {
          this.$message('非草稿状态不能删除')
          return
        }
        const strNot =
          idsNot > 0
            ? `（有${idsNot}条数据是非草稿或提交状态，将不会被删除）`
            : ''
        this.$confirm(`确定删除${ids.length}条数据? ${strNot}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (!this.direct_delete) {
            this.before_delete_hint(ids)
          } else {
            this.go_delete(ids)
          }
        })
        // 单据类型
      }
    },
    // 查看详情
    bill_show_detail(row, index) {
      this.bill_detail_add_dialog = true
      this.targetIndex = index
      this.bill_query_one(row.id)
    },

    /**
     * 单据新增前处理函数
     */
    bill_add_one_dialog_after() {}, // 点击新增按钮后得判断
    bill_add_one_dialog_before() {}, // 新增之前得判断
    // 单据新增
    bill_add_one_dialog() {
      this.bill_query_one_detail = {}
      this.bill_query_one_detail.usable = true
      this.bill_add_one_dialog_after()
      if (this.succeed) {
        this.selectedOptions = []
        this.selectedOptions = this.menu_row.Ancestor_id
        this.succeed.map(item => {
          const [prop1, prop2] = item.split('=')
          this.bill_query_one_detail[prop1] = this.menu_row[prop2]
        })
      }
      this.bill_detail_add_dialog = true
    },
    // 上一条下一条
    bill_next(flage) {
      if (flage === 1) {
        this.targetIndex--
        if (this.targetIndex < 0) {
          this.$message('这已经是第一行了')
          this.targetIndex = 0
          return
        }
      } else {
        this.targetIndex++
        if (this.targetIndex === this.bill_list.length) {
          this.targetIndex--
          this.$message('这已经是最后一行了')
          return
        }
      }
      const data = ToolClass.filter_change_data(
        this.bill_query_one_copy,
        this.bill_query_one_detail
      )
      if (!(JSON.stringify(data) === '{}')) {
        this.$confirm('您尚未保存，继续会丢失数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const id = this.bill_list[this.targetIndex].id
          this.bill_query_one(id)
        })
      } else {
        const id = this.bill_list[this.targetIndex].id
        this.bill_query_one(id)
      }
    },
    // 分页size cb
    handleSizeChange(pageSize) {
      this.per_page = pageSize - 0
      if (this.page !== 1) {
        this.page = 1
      }
      this.query_bill_list()
    },
    // 当前页 change cb
    handleCurrentChange(currentPage) {
      this.page = currentPage - 0
      this.query_bill_list()
    },
    /**
     * 查看详情
     * @param {*} path
     * @param {*} query
     */
    go_page(id) {
      // 路由跳转 path路径 query参数
      if (id) {
        this.$router.push(this.detailUrl + id)
      } else {
        this.$message('您没有选中任何数据项,请选中后再操作')
      }
    },
    /**
     * 单选某一行
     */
    row_click(row) {
      // 单击行
      this.$refs.multipleTable.clearSelection() // 先清除掉其他的
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /**
     * 点击某个单元格
     * @param {*} row
     * @param {*} column
     */
    cell_click(row, column) {
      if (column.type === 'selection') {
        this.$refs.multipleTable.toggleRowSelection(row)
      } else {
        this.$refs.multipleTable.clearSelection() // 先清除掉其他的
        this.$refs.multipleTable.toggleRowSelection(row)
      }
    },
    /**
     * 双击某一行 进入下一个页面详情
     * @param {*} currentRow
     */
    double_click_row_go_detail(currentRow) {
      if (currentRow) {
        this.go_page(currentRow[this.row_detail_id])
      }
    },
    double_click_row_show_dialog_before() {},
    /**
     * 双击某一行 弹出详情
     * @param {*}} currentRow
     */
    double_click_row_show_dialog(row) {
      this.show_item_detail(row)
    },
    show_item_detail(row, falge = true) {
      if (this.is_innner_dialog) {
        this.$emit('main_change', row)
      } else {
        // 双击行 弹出框详情
        this.double_click_row_show_dialog_before(row)
        this.bill_detail_add_dialog = true
        const index = this.bill_list.findIndex(item => {
          return item.id === row.id
        })
        this.targetIndex = index
        if (falge) {
          this.bill_query_one(row.id)
        } else {
          // 不用请求接口
          this.bill_query_one_detail = this.$pub_fun.deep_copy(row)
          this.bill_query_one_copy = this.$pub_fun.deep_copy(row)
          this.$refs.multipleTable.clearSelection()
          this.$refs.multipleTable.setCurrentRow(
            this.bill_list[this.targetIndex]
          )
          this.$refs.multipleTable.toggleRowSelection(
            this.bill_list[this.targetIndex]
          )
        }
      }
    },
    /**
     * 清空搜索框表单
     * @param {*} formName 表单的ID
     */
    reset_form() {
      this.searchParam = {}
    },
    /**
     * 重置数据
     */
    reset_data() {
      this.page = 1
      this.per_page = 10
      this.total = 0
      this.bill_list = []
      this.searchParam = {}
      this.targetRow = {}
    },
    /**
     * 刷新按钮
     */
    refresh() {
      this.query_bill_list()
    },
    bill_cancel_dialog() {
      const that = this
      this.$nextTick(function() {
        for (const item of this.bill_add_edit_dialg_form_list) {
          that.$refs[item].resetFields()
        }
      })
      this.bill_detail_add_dialog = false
    },
    // 使用 menu组件时
    /**
     * 选择左侧栏
     * @param {*} key
     * @param {*} keyPath
     */
    select_menu(key) {
      this.reset_form()
      this.reset_data()
      this.query_bill_list()
    },
    // 判断是否为空
    judge_empty(val) {
      const list = [undefined, null, '{}', '[]', 'undefined', 'null']
      return !!list.includes(val)
    },
    get_menu_list_after() {},
    /**
     * 获取左侧列表
     */
    get_menu_list(falge = true) {
      if (this.is_restful) {
        this.index_api_query_list = ''
      }
      this.$API
        .get(
          `${this.index_module_name}/${this.index_api_query_list}/`,
          {},
          this.menu_search_parm
        )
        .then(res => {
          if (Array.isArray(res.data)) {
            this.menu_list = res.data
          } else {
            this.menu_list = []
          }
          if (this.menu_list.length) {
            const id = this.menu_list[0][this.index_data_back_id]
            this.searchParam[this.index_data_id] = id
            this.$nextTick(() => {
              if (this.$refs[this.ment_tree_ref]) {
                this.$refs[this.ment_tree_ref].setCurrentKey(id)
              }
              if (this.selectedOptions !== undefined) {
                this.selectedOptions.push(id)
              }
            })
            this.menu_row = this.menu_list[0]
            this.get_menu_list_after()
            this.query_bill_list()
          } else {
            this.reset_data()
          }
        })
    },
    jump_temp(val, type) {
      if (Array.isArray(val)) {
        return true
      }
    },
    menu_query_one() {
      this.selectedOptions = []
      this.menu_row_detail_data = {}
      const routerParms = {
        routerUrl: 'id',
        data: {
          id: this.menu_row.id
        }
      }
      if (this.is_restful) {
        this.index_api_query_one = ''
      }
      this.$API
        .get(
          `${this.index_module_name}/${this.index_api_query_one}/`,
          routerParms
        )
        .then(res => {
          this.menu_dialog_edit = true
          this.menu_row_detail_data = res.data
        })
    },
    /**
     * 展开菜单时，作用在el-menu @open
     * @param {*} index
     */
    open_menu(index) {
      this.$message(this.menu_list[index].title)
    },
    // flaterArray(data) {
    //   return data.reduce((iter, val) => {
    //     const { id, title } = val
    //     const comArr = [...iter, { id, title }]
    //     return val.child ? [...comArr, ...flaterArray(val.child)] : comArr
    //   }, [])
    // },
    /**
     * 左侧菜单选中一条  //作用在 el-menu-item @click
     * @param {*}} val
     */
    click_menu_item_before(val) {}, // 点击之前
    click_menu_item_after(val) {}, // 点击之后
    click_menu_item(val) {
      this.searchParam = {}
      this.page = 1
      this.searchParam[this.index_data_id] = val.id
      this.bill_query_one_detail[this.index_data_id] = val.id
      this.click_menu_item_after(val)
      this.menu_row = val
      this.query_bill_list()
    },
    menu_add_edit_show_dialog_before() {},
    /**
     * flage 1新增 2 修改
     */
    menu_add_edit_show_dialog(flage) {
      if (flage === 2 && !this.menu_row) {
        this.$message('请先添加数据')
        return
      }
      if (flage === 2 && !this.menu_row.id) {
        this.$message('请选择菜单')
        return
      }
      switch (flage) {
        case 1:
          this.menu_add_edit_show_dialog_before()
          this.menu_row_detail_data = {}
          this.menu_dialog_edit_add_title = '新增'
          this.menu_dialog_edit = true
          break
        case 2:
          this.menu_row_detail_data = ToolClass.copy_object(this.menu_row)
          this.menu_dialog_edit_add_title = '修改'
          this.menu_dialog_edit = true
          // this.menu_dialog_edit = true
          // this.menu_query_one()
          break
      }
    },
    /**
     * 左侧菜单新增
     */
    menu_add_submit() {
      const parentId = this.menu_row.id ? this.menu_row.id : 0
      this.menu_row_detail_data.parent_id = parentId
      this.menu_save_one(this.menu_row_detail_data)
    },
    /**
     * 左侧菜单编辑
     */
    menu_edit_submit() {
      if (this.menu_dialog_edit_add_title === '新增' && this.menu_row) {
        const parentId = this.menu_row.id ? this.menu_row.id : 0
        this.menu_row_detail_data.parent_id = parentId
      }
      for (const prop in this.menu_row_detail_data) {
        if (!this.menu_row_detail_data[prop]) {
          console.log('请完善信息')
        }
      }
      this.menu_save_one(this.menu_row_detail_data)
    },
    /**
     * 左侧菜单新增或者编辑
     * @param {*} parm
     */
    menu_save_one(bodyParm) {
      if (this.is_restful) {
        this.index_api_save_one = ''
      }
      this.$API
        .post(
          `${this.index_module_name}/${this.index_api_save_one}/`,
          {},
          {},
          bodyParm
        )
        .then(() => {
          this.menu_dialog_edit = false
          this.menu_dialog_add = false
          this.menu_row_detail_data = {}
          this.menu_row = {}
          this.get_menu_list()
        })
    },
    /**
     * 左侧栏删除前特殊处理逻辑
     */
    menu_delete_before() {},
    /**
     * 左侧菜单删除
     */
    menu_delete() {
      if (!this.menu_row.id) {
        this.$message('请先选中菜单项')
        return
      }
      this.menu_delete_before()
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.before_delete_hint(
          this.menu_row.id,
          this.menu_type,
          this.go_menu_delete
        )
      })
    },
    go_menu_delete(id) {
      const routerParms = {
        routerUrl: 'id',
        data: {
          id: id
        }
      }
      if (this.is_restful) {
        this.index_api_delete_one = ''
      }
      this.$API
        .delete(
          `${this.index_module_name}/${this.index_api_delete_one}/`,
          routerParms
        )
        .then(() => {
          this.get_menu_list()
        })
    },
    // 使用树形菜单时
    // 设置表格样式
    set_table_style() {
      this.menu_height =
        document.getElementById('menu_card') &&
        document.getElementById('menu_card').clientHeight
      this.bill_height =
        document.getElementById('bill_main') &&
        document.getElementById('bill_main').clientHeight
    },
    set_row_style(row) {
      if (
        row.row.bill_status === '5' ||
        row.row.usable === false ||
        row.row.bUsable === false
      ) {
        return {
          'text-decoration': 'line-through',
          color: '#afafaf'
        }
      }
    },
    /**
     * 当选择项发生变化时会触发该事件
     */
    selection_change() {
      const parm = {
        bill_status0: this.filter_status(['0']),
        bill_status1: this.filter_status(['1']),
        bill_status01: this.filter_status(['0', '1']),
        bill_status2: this.filter_status('2'),
        bill_status3: this.filter_status('3'),
        bill_status4: this.filter_status('4'),
        bill_status5: this.filter_status('5'),
        bill_status6: this.filter_status(['6'])
      }
      this.bill_status_judge = parm
    },
    filter_status(status = []) {
      const list =
        this.$refs.multipleTable && this.$refs.multipleTable.selection
      const r =
        list &&
        list.find(cs => {
          return !status.includes(cs.bill_status)
        })
      return !!r
    },
    get_select(value, prop = 'bill_status', target_prop = 'id') {
      const list = this.$refs.multipleTable.selection
      return list.reduce((prov, next) => {
        if (next[prop] === value) {
          prov.push(next[target_prop])
        }
        if (!value) {
          prov.push(next[target_prop])
        }
        return prov
      }, [])
    },
    /**
     * 单据审核
     */
    bills_audit() {
      const list = this.get_select('1')
      if (!list.length) {
        this.$message('请选择单据状态为[提交]的数据项！')
        return
      }
      this.audit_bills(list).then(() => {
        this.$message.success('审核成功')
        this.query_bill_list()
      })
    },
    // 单据发送
    bill_send() {
      let is_system = true
      const lists = this.$refs.multipleTable.selection
      lists.map((item) => {
        if (item.is_system) {
          is_system = false
        }
      })
      if (!is_system) {
        this.$message('您选中的数据有系统单不可改变状态,请检查数据')
        return
      }
      const list = this.get_select('0')
      if (!list.length) {
        this.$message('请选择单据状态为[未发送]的数据项！')
        return
      }
      this.sendedi_bills(list, this.send).then(() => {
        this.query_bill_list()
      })
    },
    // 单据完结
    bill_send_finish() {
      let is_system = true
      let me_order = true
      const lists = this.$refs.multipleTable.selection
      lists.map((item) => {
        if (item.is_system) {
          is_system = false
        }
        if (item.me_order) {
          me_order = false
        }
      })
      if (!is_system) {
        this.$message('您选中的数据有系统单不可操作,请检查数据')
        return
      }
      if (!me_order) {
        this.$message('您选中的数据有供应商为本公司的客户单不可操作,请检查数据')
        return
      }
      const list = this.get_select('1')
      if (!list.length) {
        this.$message('请选择单据状态为[已发送]的数据项！')
        return
      }
      const param = {}
      param.ids_list = list
      this.$API.post(`mesAPI/${this.send}/finish/`, {}, {}, param).then(res => {
        let success = ''
        if (this.send === 'pu_order') {
          success = 'success_orders'
        } else {
          success = 'success_shipments'
        }
        const a = res.data[success].join(',')
        this.$message.success(`订单${a}已完结`)
        this.query_bill_list()
      })
    },
    /**
     * 反审
     */
    bills_un_audit() {
      const list = this.get_select('2')
      if (!list.length) {
        this.$message('请选择单据状态为[已审核]的数据项！')
        return
      }
      this.un_audit_bills(list).then(() => {
        this.$message.success('反审成功')
        this.query_bill_list()
      })
    },
    // 撤回
    bills_un_audit_edi() {
      let is_system = true
      let me_order = true
      const lists = this.$refs.multipleTable.selection
      lists.map((item) => {
        if (item.is_system) {
          is_system = false
        }
        if (item.me_order) {
          me_order = false
        }
      })
      if (!is_system) {
        this.$message('您选中的数据有系统单不可撤回,请检查数据')
        return
      }
      if (!me_order && this.module_name === '/mesAPI/pu_order') {
        this.$message(`已选中的数据下有供应商为本公司的采购单，不可以撤回，请检查数据`)
        return
      }
      if (!me_order && this.module_name === '/mesAPI/im_shipment') {
        this.$message(`已选中的数据下有客户为本公司的出貨单，不可以撤回， 请检查数据`)
        return
      }
      const list = this.get_select('1')
      if (!list.length) {
        this.$message('请选择单据状态为[已发送]的数据项！')
        return
      }
      this.edi_un_audit_bills(list, this.send).then(() => {
        this.query_bill_list()
      })
    },
    /**
     * 关闭
     */
    bills_close_bills() {
      const list = this.get_select('1')
      if (!list.length) {
        this.$message('请选择单据状态为[已完结]的数据项！')
        return
      }
      this.close_bills(list).then(() => {
        this.$message.success('关闭成功')
        this.query_bill_list()
      })
    },
    /**
     * 取消关闭
     */
    bills_un_close_bills() {
      const list = this.get_select('6')
      if (!list.length) {
        this.$message('请选择单据状态为[关闭]的数据项！')
        return
      }
      this.un_close_bills(list).then(() => {
        this.$message.success('取消关闭成功')
        this.query_bill_list()
      })
    },
    // {iHintType: 0, sHint: ""}
    // iHintType: 1, sHint: "报错了"}
    // {iHintType: 2, sHint: "因为这样那样，确定要删除吗"}
    // bill_type : 单据类型 在给自的业务页面设置
    async go_delete(bill_ids = []) {
      // 把单据状态为已送审的取消送审再删除
      const list = this.get_select('1')
      if (list.length) {
        await this.un_send_bills(list)
      }
      const parm_delete = {
        ids_list: bill_ids
      }
      if (this.is_restful) {
        this.api_delete_list = ''
      }
      this.$API
        .delete(
          `${this.module_name}/${this.api_delete_list}/`,
          {},
          {},
          parm_delete
        )
        .then(res => {
          this.$message('删除成功')
          const page_all = this.total / this.per_page // 总页数
          const cutt_num = this.total - this.per_page * (this.page - 1)
          const r1 = page_all <= this.page // 判断当前也是否是最后一页
          const r2 = cutt_num === bill_ids.length
          if (r1 && r2) {
            this.page = 1
          }
          this.init_query()
          this.bill_delete_list_after()
        })
    },
    before_delete_hint(
      bill_ids = [],
      bill_type = this.bill_type,
      callback = this.go_delete
    ) {
      if (!(bill_type + '')) {
        this.$message('请设置bill_type')
        return
      }
      const parm = {
        bill_type,
        bill_ids,
        operator_id: 0
      }
      this.$API.post('mesAPI/before_delete_hint/', {}, {}, parm).then(res => {
        const { iHintType, sHint } = res.data
        if (iHintType === 0) {
          callback(bill_ids)
          // 校验通过
        } else if (iHintType === 1) {
          this.$message.error(sHint)
        } else if (iHintType === 2) {
          this.$confirm(`${sHint}`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            callback(bill_ids)
          })
        } else if (iHintType === 3) {
          this.$message.warning(sHint)
        }
      })
    },
    // 获取当前时间
    getNowFormatDate() {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },
    /**
     * 获取上一个月
     *
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    getPreMonth(date) {
      var arr = date.split('-')
      var year = arr[0] // 获取当前日期的年份
      var month = arr[1] // 获取当前日期的月份
      var day = arr[2] // 获取当前日期的日
      var year2 = year
      var month2 = parseInt(month) - 1
      if (month2 === 0) {
        year2 = parseInt(year2) - 1
        month2 = 12
      }
      var day2 = day
      var days2 = new Date(year2, month2, 0)
      days2 = days2.getDate()
      if (day2 > days2) {
        day2 = days2
      }
      if (month2 < 10) {
        month2 = '0' + month2
      }
      var t2 = year2 + '-' + month2 + '-' + day2
      return t2
    },
    /**
     * 获取下一个月
     *
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    getNextMonth(date) {
      var arr = date.split('-')
      var year = arr[0] // 获取当前日期的年份
      var month = arr[1] // 获取当前日期的月份
      var day = arr[2] // 获取当前日期的日
      var year2 = year
      var month2 = parseInt(month) + 1
      if (month2 === 13) {
        year2 = parseInt(year2) + 1
        month2 = 1
      }
      var day2 = day
      var days2 = new Date(year2, month2, 0)
      days2 = days2.getDate()
      if (day2 > days2) {
        day2 = days2
      }
      if (month2 < 10) {
        month2 = '0' + month2
      }

      var t2 = year2 + '-' + month2 + '-' + day2
      return t2
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      let _sums = 0
      for (const item of data) {
        for (const prop in item) {
          if (item[prop]) {
            _sums++
            break
          }
        }
      }
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index === 1) {
          sums[index] = _sums
          return
        }
        const { property } = column
        this.summaryAttr.forEach(sum => {
          const { type, attr } = sum
          if (property === attr) {
            const values = data.map(item => {
              const val = Number(item[column.property])
              return isNaN(val) ? 0 : val
            })
            if (values.length) {
              const count = values.reduce((prev, curr) => {
                return prev + curr
              }, 0)
              switch (type) {
                case 'sum':
                  sums[index] = count
                  break
                case 'ava':
                  sums[index] = _sums === 0 ? '-' : (count / _sums).toFixed(2)
                  break
              }
            } else {
              sums[index] = '-'
            }
          }
        })
      })
      return sums
    }
  }
}
export default utilUc
