import ToolClass from '@utils/toolClass'
import Base from '@basicClass/base'
import billUtil from './bill_util'
const utilUc = {
  mixins: [Base, billUtil],
  data() {
    return {
      bill_hdr: {
        data: {},
        table_name: ''
      }, // 表头明细
      bill_dtl: [], // 单表明细
      query_bill_parm_id: 'bill_id',
      required_field_bill_dtl: {}, // 明细必填字段
      required_field_bill_hdr: {}, // 头表必填字段
      bill_not_check_hdr: {}, // 头部填充字段
      bill_dtl_single_detail: {}, // 单据新增行
      bill_dtl_empty: [], // id:0 默认明细
      bill_height: 100,
      api_bill_base_query: 'query_bill',
      api_bill_base_save: 'save_bill',
      dataParm: {},
      bill_hdr_copy: {},
      bill_hdr_data_copy: {},
      bill_dtl_copy: [],
      delete_prop: {}, // 过滤表的字典{'item_sear':'这张表废弃不显示'}
      bill_dtl_list_dtl_dialog: [] // 单据明细的弹出框
    }
  },
  computed: {
    /**
     * 控制单据是否可编辑
     */
    bill_editable() {
      return !(
        this.bill_hdr.data.bill_status === '0' ||
        this.bill_hdr.data.bill_status === '1' ||
        !this.bill_hdr.data.bill_status
      )
    },
    /**
     * 新增时候的状态
     */
    bill_add_status() {
      return this.bill_hdr.data.id
    },
    /**
     * 计算这个列表是否有有效值（id）
     */
    bill_list_empty() {
      let s
      this.bill_dtl.map(item => {
        s = item.data.find(item => {
          return item.id
        })
      })
      return s
    },
    bill_is_send() {
      const data = this.bill_hdr.data
      return data.id !== '0' && data.id && data.bill_status === '0'
    },
    bill_back_send() {
      const data = this.bill_hdr.data
      return data.id !== '0' && data.id && data.bill_status === '1'
    },
    bill_status_0() {
      const data = this.bill_hdr.data
      return !data.id && data.bill_status === '0'
    },
    /**
     * 审核按钮
     */
    bill_status_1() {
      const data = this.bill_hdr.data
      return data.bill_status === '1'
    },
    /**
     * 取消审核按钮
     */
    bill_status_2() {
      const data = this.bill_hdr.data
      return data.bill_status === '2'
    },
    bill_status_01() {
      const data = this.bill_hdr.data
      return data.id && (data.bill_status === '0' || data.bill_status === '1')
    },
    bill_status_6() {
      const data = this.bill_hdr.data
      return data.id && data.bill_status === '6'
    }
  },
  mounted() {
    this.set_table_style()
  },
  methods: {
    /**
     * 整单查询
     * @param {*} billId
     */
    query_bill(billId = this.bill_hdr.data.id) {
      if (billId !== '0') {
        // 详情
        const routerParms = {
          routerUrl: this.query_bill_parm_id,
          data: {
            [this.query_bill_parm_id]: billId
          }
        }
        this.base_bill_query(routerParms).then(res => {
          if (!res.data) return
          this.bill_hdr = res.data.header
          const parm = {}
          res.data.childs.map((item, index) => {
            for (const prop in item) {
              if (item[prop] && Reflect.has(this.delete_prop, item[prop])) {
                res.data.childs.splice(index, 1) // 删除掉 不必要的明细
              }
            }
            // 按照表名分组成字典形式
            if (
              !parm[item.table_name] &&
              !Reflect.has(this.delete_prop, item.table_name)
            ) {
              parm[item.table_name] = item
            }
          })
          this.dataParm = parm
          this.bill_dtl = res.data.childs
          this.copyData()
          this.item_data_reset_empty(this.bill_dtl)
        })
      } else {
        // 新增的情况2
        this.bill_hdr = ToolClass.copy_object(this.bill_hdr_empty)
        this.bill_dtl = ToolClass.copy_object(this.bill_dtl_empty)
        delete this.bill_hdr.data.id
        this.copyData()
        this.item_data_reset_empty(this.bill_dtl)
      }
    },
    filter_dtl_data_no_cheack() {
      const parm = {
        header: {
          table_name: this.bill_hdr.table_name,
          data: []
        },
        childs: []
      }
      // 单据头修改的数据
      parm.header.data = ToolClass.filter_change_data(
        this.bill_hdr_data_copy,
        this.bill_hdr.data,
        this.bill_not_check_hdr
      )
      // 明细修改对数据
      parm.childs = ToolClass.filterData(this.bill_dtl_copy, this.bill_dtl)
      return parm
    },
    filter_dtl_data() {
      const parm = {
        header: {
          table_name: this.bill_hdr.table_name,
          data: []
        },
        childs: []
      }
      // 校验 单据头
      const r = this.validate_bill_hdr(
        this.bill_hdr.data,
        this.required_field_bill_hdr
      )
      if (!r) {
        return
      }
      // 单据头修改的数据 这里面没有校验是否必传字段
      parm.header.data = ToolClass.filter_change_data(
        this.bill_hdr_data_copy,
        this.bill_hdr.data,
        this.bill_not_check_hdr
      )
      // 明细修改对数据 里面有校验必传字段
      parm.childs = ToolClass.filterData(
        this.bill_dtl_copy,
        this.bill_dtl,
        this.required_field_bill_dtl
      )
      return parm
    },
    message_success(text) {
      this.$message({
        showClose: true,
        message: text,
        type: 'success'
      })
    },
    // 保存整张单据
    bill_save() {
      const parm = this.filter_dtl_data()
      console.log(parm)
      if (!parm || !parm.childs) {
        return
      }
      this.base_bill_save({}, {}, parm, this.api_bill_base_save + '/true').then(
        res => {
          // 处理保存后的逻辑
          this.deal_data(res.data)
          this.message_success('保存成功！')
        }
      )
    },
    /**
     * 刷新
     */
    bill_refresh() {
      if (this.bill_hdr.data.id) {
        const result = this.is_leave_page()
        if (!result) {
          this.query_bill(this.bill_hdr.data.id)
        } else {
          result
            .then(() => {
              this.query_bill(this.bill_hdr.data.id)
            })
            .catch(() => {})
        }
      }
    },
    /**
     * 上一单下一单 flage 1 上 flage2 下
     * @param {*} flage
     */
    get_next_by_bill_no(flage) {
      const routerParms = {
        routerUrl: 'bill_no',
        data: {
          bill_no: this.bill_hdr.data.bill_no
        }
      }
      const aip = flage === 1 ? 'last_order' : 'next_order'
      this.base_bill_query(routerParms, {}, aip, this.module_name).then(res => {
        if (res.data === null) {
          const message =
            flage === 1 ? '这已经是第一条了' : '这已经是最后一条了'
          this.$message(message)
          return
        }

        this.bill_hdr = res.data.header
        this.bill_dtl = res.data.childs
        this.copyData()
        this.item_data_reset_empty(this.bill_dtl)
      })
    },
    bill_next_up_down(flage) {
      const result = this.is_leave_page()
      if (!result) {
        this.get_next_by_bill_no(flage)
      } else {
        result
          .then(() => {
            this.get_next_by_bill_no(flage)
          })
          .catch(() => {})
      }
    },
    /**
     * 初始化数据
     * @param {*} list
     */
    item_data_reset_empty(list) {
      list.map(item => {
        if (item.data.length < 5) {
          const n = 5 - item.data.length
          for (let i = 0; i < n; i++) {
            item.data.push({})
          }
        }
      })
    },
    copyData() {
      this.bill_hdr_copy = ToolClass.copy_object(this.bill_hdr)
      this.bill_hdr_data_copy = ToolClass.copy_object(this.bill_hdr.data)
      this.bill_dtl_copy = ToolClass.copy_object(this.bill_dtl)
    },
    /**
     * 校验单据头信息(保存前校验)
     */
    validate_bill_hdr(data, objExcept = {}) {
      let result = true
      for (const key in objExcept) {
        if (!data[key]) {
          this.$message(`请您完善: ${objExcept[key]}`)
          result = false
          return
        }
      }
      return result
    },
    /**
     * 校验单据明细信息
     */
    validate_bill_dtl(data, objExcept = {}) {
      let result = true
      for (const item of data) {
        if (item.iUpdateStatus !== 4) {
          for (const key in objExcept) {
            if (!item[key]) {
              this.$message(`请您完善: ${objExcept[key]}`)
              result = false
              return
            }
          }
        }
      }
      return result
    },
    /**
     * 单据明细本地新增一行
     * @param {*} bCopy 是否复制
     */
    add_new_bill_dtl(index, data) {
      // let entity
      // entity = Object.assign({}, this.bill_dtl_single_detail)
      data.unshift({})
    },
    // 删除订单 --- 废弃
    delete_bill() {
      const routerParm = {
        routerUrl: 'id',
        data: {
          id: this.bill_hdr.data.id
        }
      }
      if (!this.bill_hdr.data.id) {
        this.$message('不能进行删除')
        return
      }
      this.$confirm('确定删除该单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$API
          .delete(`${this.module_name}/delete_one/`, routerParm)
          .then(res => {
            this.tabRemove()
          })
          .catch(() => {})
      })
    },
    delete_bill_add_empty() {
      const routerParm = {
        routerUrl: 'id',
        data: {
          id: this.bill_hdr.data.id
        }
      }
      if (!this.bill_hdr.data.id) {
        this.$message('不能进行删除')
        return
      }
      this.$confirm('确定删除该单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$API
          .delete(`${this.module_name}/delete_one/`, routerParm)
          .then(res => {
            this.bill_hdr = ToolClass.copy_object(this.bill_hdr_empty)
            this.bill_dtl = ToolClass.copy_object(this.bill_dtl_empty)
            delete this.bill_hdr.data.id

            this.copyData()
            this.item_data_reset_empty(this.bill_dtl)
          })
          .catch(() => {})
      })
    },
    /**
     * 删除单据明细当前行
     */
    delete_curr_bill_dtl(index, data) {
      if (data.length <= 5) {
        data[index] = {}
        this.$set(data, index, data[index])
      } else {
        data.splice(index, 1)
      }
    },
    replaceURL(path, id) {
      // 路由跳转 path路径 query参数
      const oldId = this.$route.params.id
      if (oldId === id) {
        return
      }
      this.$router.replace(path + id) // 由于公用一个页面这里建议使用 replace处理
    },
    set_table_style() {
      const containerHeight =
        document.getElementById('container') &&
        document.getElementById('container').clientHeight
      const headerHeight =
        document.getElementById('header') &&
        document.getElementById('header').clientHeight
      this.bill_height = containerHeight - headerHeight - 40 - 15 - 10
    },
    // 获取明细所有选中的list
    multiple_select_dtl_table() {
      return this.$refs.multiple_dtl_table.selection
    },
    tabRemove() {
      const index = this.$store.getters.activeTabIndex
      this.$store.commit('deleteHeaderTab', { that: this, index })
    },
    /**
     * 合计字段
     * @param {d\} param
     */
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        this.summaryAttr.forEach(attr => {
          if (column.property === attr) {
            const values = data.map(item => Number(item[column.property]))
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              // sums[index] += ' '
            } else {
              sums[index] = '-'
            }
          }
        })
      })
      return sums
    },
    delete_one(id) {
      this.base_delete_one(id).then(() => {
        this.tabRemove()
      })
    },
    delete_list(ids) {
      const parm = { id_list: ids }
      this.base_delete_list(parm).then(() => {
        // 删除后的处理逻辑
      })
    },
    is_leave_page() {
      const parm = this.filter_dtl_data_no_cheack()
      if (!parm) {
        return
      }
      console.log(parm)
      const dataHdr = parm.header.data
      const p1 = dataHdr.id && Object.keys(dataHdr).length === 1
      const p2 = !dataHdr.id && !Object.keys(dataHdr).length
      if ((p1 || p2) && !parm.childs.length) {
        return
      } else {
        return this.$confirm('数据尚未保存,离开将会丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      }
    },
    add_bill() {
      if (this.bill_status_01 || this.bill_status_0) {
        const result = this.is_leave_page()
        console.log(result)
        if (!result) {
          this.deal_data()
        } else {
          result.then(() => {
            this.deal_data()
          })
        }
      }
    },
    bill_save_temporary() {
      const parm = this.filter_dtl_data_no_cheack()
      const dataHdr = parm.header.data
      const p1 = dataHdr.id && Object.keys(dataHdr).length === 1
      const p2 = !dataHdr.id && !Object.keys(dataHdr).length
      if ((p1 || p2) && !parm.childs.length) {
        this.$message('数据未做改变，请重新检查')
        return
      }
      this.base_bill_save(
        {},
        {},
        parm,
        this.api_bill_base_save + '/false'
      ).then(res => {
        this.deal_data(res.data)
      })
    },
    deal_data(data) {
      if (data) {
        this.bill_hdr = data.header
        this.bill_dtl = data.childs
        this.copyData()
        this.item_data_reset_empty(this.bill_dtl)
      } else {
        this.bill_hdr = ToolClass.copy_object(this.bill_hdr_empty)
        this.bill_dtl = ToolClass.copy_object(this.bill_dtl_empty)
        this.copyData()
        this.item_data_reset_empty(this.bill_dtl)
      }
    },
    /**
     * 单据审核
     */
    bill_audit() {
      this.audit_bills(this.bill_hdr.data.id).then(() => {
        this.query_bill(this.bill_hdr.data.id)
      })
    },
    /**
     * 反审
     */
    bill_un_audit() {
      this.un_audit_bills(this.bill_hdr.data.id).then(() => {
        this.query_bill(this.bill_hdr.data.id)
      })
    },
    /**
     * 完结
     */
    bill_close_bills() {
      this.close_bills(this.bill_hdr.data.id).then(() => {
        this.query_bill(this.bill_hdr.data.id)
      })
    },
    bill_un_close_bills() {
      this.un_close_bills(this.bill_hdr.data.id).then(() => {
        this.query_bill(this.bill_hdr.data.id)
      })
    },
    /**
     *
     * 复制整单
     */
    bill_copy_data_handle() {
      const hdr = ToolClass.copy_object(this.bill_hdr_copy)
      delete hdr.data.id
      delete hdr.data.bill_status
      delete hdr.data.bill_no
      const billDtl = ToolClass.copy_object(this.bill_dtl_copy)
      for (const item of billDtl) {
        for (const jtem of item.data) {
          delete jtem.id
          delete jtem.bill_id
        }
      }
      this.bill_hdr = hdr
      this.bill_hdr_data = hdr.data
      this.bill_dtl = billDtl
      this.bill_hdr_copy = ToolClass.copy_object(this.bill_hdr_empty)
      this.bill_hdr_data_copy = ToolClass.copy_object(this.bill_hdr_empty.data)
      this.bill_dtl_copy = ToolClass.copy_object(this.bill_dtl_empty)
      this.item_data_reset_empty(this.bill_dtl)
    },
    bill_copy() {
      const result = this.is_leave_page()
      if (!result) {
        this.bill_copy_data_handle()
      } else {
        result
          .then(() => {
            this.bill_copy_data_handle()
          })
          .catch(() => {})
      }
    },
    /**
     * 删除 然后清空页面
     */
    bill_delete_empty_data() {
      this.$confirm('确定删除该单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$API
          .delete(`${this.module_name}/delete_one/${this.bill_hdr.data.id}/`)
          .then(res => {
            this.bill_hdr = ToolClass.copy_object(this.bill_hdr_empty)
            this.bill_dtl = ToolClass.copy_object(this.bill_dtl_empty)
            delete this.bill_hdr.data.id
            this.copyData()
            this.item_data_reset_empty(this.bill_dtl)
          })
      })
    },
    // 单据-单条明细详情查询
    query_list_dtl_row_dialog() {
      const routerParms = {
        routerUrl: 'id',
        data: {
          id: this.bill_dtl_current_row.id
        }
      }
      this.bill_dtl_list_dtl_dialog = []
      this.$API
        .get(
          `${this.module_name_dtl_row_data_dialog}/query_list_by/item_id/`,
          routerParms
        )
        .then(res => {
          this.visible_dtl_row_dialog = true
          this.bill_dtl_list_dtl_dialog = res.data
        })
    },
    // 双击单据明细-然后弹出明细
    double_click_row_dtl(row) {
      if (!row.id) {
        this.$message('暂无数据')
        return
      }
      this.bill_dtl_current_row = row
      this.query_list_dtl_row_dialog()
    },
    // 单击 选中单据的某一条明细- 设置单行选中
    single_click_row_dtl_dialog(row) {
      this.$refs.multiple_table_inner_delete.toggleRowSelection(row)
    },
    // 批量删除 单据弹出框明细
    delete_list_dtl_dialog() {
      const list = this.$refs.multiple_table_inner_delete.selection
      if (!list.length) {
        this.$message('暂无数据')
        return
      }
      const ids = []
      for (const element of list) {
        ids.push(element.id)
      }
      const parm = { id_list: ids }
      this.$API
        .delete(
          `${this.module_name_dtl_row_data_dialog}/delete_list/`,
          {},
          {},
          { data: parm }
        )
        .then(() => {
          this.query_bill()
          this.visible_dtl_row_dialog = false
        })
    }
  }
}
export default utilUc
