<template>
  <template-page
    v-if="showTable"
    ref="pageRef"
    :get-list="[getList1, getList2][pageLevel]"
    :exportList="[exportList1, exportList2][pageLevel]"
    :options-evens-group="[optionsEvensGroup1, optionsEvensGroup2][pageLevel]"
    :operation="[operation1, operation2][pageLevel]()"
    :expCode="['exp', 'detailExp'][pageLevel]"
    :table-attributes="tableAttributes"
    :table-events="tableEvents"
    :moreParameters="moreParameters"
    :column-parsing="columnParsing"
  >
    <div slot="moreSearch" v-if="pageLevel == 0">
      <el-radio-group v-model="tagStatus" size="mini" @change="changeType">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button label="NO">未汇总</el-radio-button>
        <el-radio-button label="YES">已汇总</el-radio-button>
      </el-radio-group>
      <br /><br />
    </div>
    <div class="cartographer_big">
      <el-dialog title="费用明细" width="100%" :modal="false" :visible.sync="formBool" :before-close="handleClose">
        <zj-page-container v-if="formBool">
          <zj-page-fill class="neibuview">
            <zj-form-container ref="formRef" :form-data="formData" :form-attributes="{ size: 'mini' }">
              <zj-form-module title="基本信息" label-width="130px" :form-data="formData" :form-items="formItems" />
            </zj-form-container>
          </zj-page-fill>
          <div>
            <div style="box-sizing: border-box; padding: 10px; text-align: right">
              <el-button size="mini" @click="handleClose">取 消</el-button>
              <el-button v-if="!formEdit" size="mini" @click="formConfirm" type="primary">确 定</el-button>
            </div>
          </div>
        </zj-page-container>
      </el-dialog>
    </div>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import ImageUpload from '@/components/file-upload'
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
import {
  settleExpenseGatherList,
  settleExpenseGatherListExport,
  settleExpenseImport,
  settleExpenseMonthGather,
  settleExpenseList,
  settleExpenseListExport,
  settleExpenseGatherBatchDel,
  settleExpenseBatchDel,
  settleExpenseSave
} from '@/api/costPerDimension'
import { commonTemplateDownload } from '@/api/common.js'
import { memberListPageV2 } from '@/api/masterManagement'
export default {
  components: { TemplatePage, ImageUpload },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true,
        selectable: this.selectable
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      pageLevel: 0,
      showTable: true,
      collectItem: {},
      formData: {
        companyWechatName: JSON.parse(localStorage.getItem('greemall_user')).companyName
      },
      formBool: false,
      formEdit: false,
      workerList: [],
      tagStatus: this?.pageCode || ''
    }
  },
  computed: {
    optionsEvensGroup1() {
      return [
        [
          [
            this.optionsEvensAuth('batchSummary', {
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.warning('请勾选工单')
                  return
                }
                this.$prompt('汇总名称', '汇总', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  inputPattern: /\S/,
                  inputErrorMessage: '名称不能为空'
                })
                  .then(({ value }) => {
                    settleExpenseMonthGather({
                      ids: this.recordSelected.map(item => item.id),
                      name: value
                    }).then(res => {
                      this.$message({
                        type: 'success',
                        message: '操作成功！'
                      })
                      this.$refs?.pageRef?.refreshList()
                    })
                  })
                  .catch(() => {})
              }
            })
          ],
          [
            this.optionsEvensAuth(['import', 'download1', 'download2', 'download3', 'download4'], {
              name: '导入费用',
              click: () => {}
            }),
            this.optionsEvensAuth('import', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(settleExpenseImport, moduleName)
                }
              }
            }),
            this.optionsEvensAuth('download1', {
              click: () => {
                commonTemplateDownload({ name: '师傅费用结算导入模板(其它).xlsx' }, `师傅费用结算导入模板(其它)`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            }),
            this.optionsEvensAuth('download2', {
              click: () => {
                commonTemplateDownload(
                  { name: '师傅费用结算导入模板(安装其它).xlsx' },
                  `师傅费用结算导入模板(安装其它)`
                )
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            }),
            this.optionsEvensAuth('download3', {
              click: () => {
                commonTemplateDownload(
                  { name: '师傅费用结算导入模板(安装家用空调).xlsx' },
                  `师傅费用结算导入模板(安装家用空调)`
                )
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            }),
            this.optionsEvensAuth('download4', {
              click: () => {
                commonTemplateDownload({ name: '师傅费用结算导入模板(维修).xlsx' }, `师傅费用结算导入模板(维修)`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            })
          ]
        ]
      ]
    },
    optionsEvensGroup2() {
      return [
        [
          [
            {
              name: '返回汇总页面',
              click: () => {
                this.pageLevel = 0
              }
            }
          ]
        ],
        ...(() => {
          if (this.collectItem.status != 'YES') {
            return [
              [
                [
                  this.optionsEvensAuth('detailAdd', {
                    click: () => {
                      this.formBool = true
                      this.formEdit = false
                      this.getWorkers()
                    }
                  })
                ],
                [
                  this.optionsEvensAuth('detailBatchDel', {
                    click: () => {
                      if (this.recordSelected.length === 0) {
                        this.$message.warning('请勾选工单')
                        return
                      }
                      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                      })
                        .then(() => {
                          settleExpenseBatchDel(this.recordSelected.map(item => item.id)).then(res => {
                            this.$message({
                              type: 'success',
                              message: '删除成功！'
                            })
                            this.$refs?.pageRef?.refreshList()
                          })
                        })
                        .catch(() => {})
                    }
                  })
                ]
              ]
            ]
          }
          return []
        })()
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [
        {
          name: 'el-input',
          md: 12,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '网点名称',
            prop: 'importWebsitName',
            rules: []
          }
        },
        {
          name: 'el-date-picker',
          md: 6,
          attributes: {
            type: 'month',
            disabled: this.formEdit,
            'value-format': 'yyyy-MM'
          },
          formItemAttributes: {
            label: '发放月份',
            prop: 'sendMonth',
            rules: [...required]
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '费用类型',
            prop: 'typeName',
            rules: [...required]
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '安装/维修品类',
            prop: 'category',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '维修自编号',
            prop: 'repairCustomCode',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '内机条码',
            prop: 'insideCode',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '内机名称',
            prop: 'insideName',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '基础安装/维修费用',
            prop: 'baseAmount',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '辅材达标',
            prop: 'materialAmount',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '评价数据达标',
            prop: 'appraiseAmount',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '旧机回收达标',
            prop: 'recoveryAmount',
            rules: this.formData.categoryType === 'INSTALL_HOME' ? [...required] : []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '其它',
            prop: 'otherAmount',
            rules: []
          }
        },
        {
          md: 6,
          name: 'slot-component',
          formItemAttributes: {
            label: '合计金额',
            prop: 'totalAmount',
            rules: []
          },
          attributes: {},
          render: (h, { props, onInput }) => {
            this.formData.totalAmount =
              Number(this.formData.baseAmount || 0) +
              Number(this.formData.materialAmount || 0) +
              Number(this.formData.appraiseAmount || 0) +
              Number(this.formData.otherAmount || 0) +
              Number(this.formData.recoveryAmount || 0)
            return (
              <el-input value={this.formData.totalAmount} disabled={true} size="mini" placeholder="请输入"></el-input>
            )
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '工单编号',
            prop: 'orderNo',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '销售单号',
            prop: 'salesOrderNo',
            rules: []
          }
        },
        {
          name: 'el-date-picker',
          md: 6,
          attributes: {
            type: 'date',
            disabled: this.formEdit,
            'value-format': 'yyyy-MM-dd HH:mm:ss'
          },
          formItemAttributes: {
            label: '安装/维修日期',
            prop: 'workDate',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '销售类型',
            prop: 'salesType',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 12,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '维修内容',
            prop: 'repairContent',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '客户名称',
            prop: 'userName',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '客户电话',
            prop: 'userMobile',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 24,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '客户地址',
            prop: 'userAddress',
            rules: []
          }
        },
        {
          name: 'zj-select',
          options: this.workerList,
          md: 6,
          attributes: {
            disabled: this.formEdit,
            placeholder: '请选择',
            clearable: true,
            filterable: true,
            blurNoMatchText: true,
            blurNoMatchInputBorderColor: ''
          },
          formItemAttributes: {
            label: '工程师1名称',
            prop: 'workerId1',
            rules: [...required]
          },
          events: {
            change: val => {
              var data = this.workerList.find(item => item.value == val)?.data
              if (data) {
                this.formData.workerName1 = data?.workerName || ''
                this.formData.workerMobile1 = data?.workerMobile || ''
              } else {
                this.formData.workerName1 = val
                this.formData.workerMobile1 = ''
              }
            }
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '工程师1电话',
            prop: 'workerMobile1',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '工程师1结算比例',
            prop: 'workerSettleRate1',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '工程师1结算金额',
            prop: 'workerSettleAmount1',
            rules: []
          }
        },
        {
          name: 'zj-select',
          options: this.workerList,
          md: 6,
          attributes: {
            disabled: this.formEdit,
            placeholder: '请选择',
            clearable: true,
            filterable: true,
            blurNoMatchText: true,
            blurNoMatchInputBorderColor: ''
          },
          formItemAttributes: {
            label: '工程师2名称',
            prop: 'workerId2',
            rules: []
          },
          events: {
            change: val => {
              var data = this.workerList.find(item => item.value == val)?.data
              if (data) {
                this.formData.workerName2 = data?.workerName || ''
                this.formData.workerMobile2 = data?.workerMobile || ''
              } else {
                this.formData.workerName2 = val
                this.formData.workerMobile2 = ''
              }
            }
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '工程师2电话',
            prop: 'workerMobile2',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '工程师2结算比例',
            prop: 'workerSettleRate2',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '工程师2结算金额',
            prop: 'workerSettleAmount2',
            rules: []
          }
        },
        {
          name: 'el-input',
          md: 24,
          attributes: {
            disabled: this.formEdit
          },
          formItemAttributes: {
            label: '备注',
            prop: 'remark',
            rules: []
          }
        }
      ]
    }
  },
  watch: {
    pageLevel() {
      this.showTable = false
      this.$nextTick(() => {
        this.showTable = true
      })
    }
  },
  created() {
    if (this.pageCode) {
      this.tagStatus = this?.pageCode
    }
  },
  methods: {
    changeType(val) {
      this.$refs.pageRef.refreshList()
    },
    getList1(p, cb) {
      var pam = JSON.parse(JSON.stringify(p))
      try {
        if (this.tagStatus) {
          pam.params.push({ param: 'a.status', compare: '=', value: this.tagStatus })
        }
        cb && cb(pam)
        return settleExpenseGatherList(pam)
      } catch (err) {}
    },
    exportList1: settleExpenseGatherListExport,
    getList2(p, cb) {
      var pam = JSON.parse(JSON.stringify(p))
      try {
        pam.params.push({ param: 'a.settle_expense_id', compare: '=', value: this.collectItem.id })
        cb && cb(pam)
        return settleExpenseList(pam)
      } catch (err) {}
    },
    exportList2: settleExpenseListExport,
    selectable(row, index) {
      if (this.pageLevel) {
        return this?.collectItem?.status != 'YES'
      }
      return !['YES'].includes(Object.entries(row.selectMapData.status).find(([key, val]) => val == row.status)?.[0])
    },
    operation1() {
      return this.operationBtn({
        detail: {
          click: ({ row, index, column }) => {
            this.collectItem = { ...row }
            this.pageLevel = 1
          }
        },
        summary: {
          conditions: ({ row, index, column }) => {
            return row.status != 'YES'
          },
          click: ({ row, index, column }) => {
            this.$prompt('汇总名称', '汇总', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPattern: /\S/,
              inputErrorMessage: '名称不能为空'
            })
              .then(({ value }) => {
                settleExpenseMonthGather({
                  ids: [row.id],
                  name: value
                }).then(res => {
                  this.$message({
                    type: 'success',
                    message: '操作成功！'
                  })
                  this.$refs?.pageRef?.refreshList()
                })
              })
              .catch(() => {})
          }
        },
        del: {
          prompt: '此操作将永久删除数据, 是否继续?',
          conditions: ({ row, index, column }) => {
            return row.status != 'YES'
          },
          click: ({ row, index, column }) => {
            settleExpenseGatherBatchDel([row.id]).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
              this.$refs?.pageRef?.refreshList()
            })
          }
        }
      })
    },
    operation2() {
      return this.operationBtn({
        detailEdit: {
          conditions: ({ row, index, column }) => {
            return row.status != 'YES'
          },
          click: ({ row, index, column }) => {
            this.formData = {
              ...row,
              ...(() => {
                var obj = {}
                if (!row.workerId1 && row.workerName1) {
                  obj.workerId1 = row.workerName1
                }
                if (!row.workerId2 && row.workerName2) {
                  obj.workerId2 = row.workerName2
                }
                return obj
              })()
            }
            this.formEdit = false
            this.formBool = true
            this.getWorkers()
          }
        },
        detailDel: {
          prompt: '此操作将永久删除数据, 是否继续?',
          conditions: ({ row, index, column }) => {
            return row.status != 'YES'
          },
          click: ({ row, index, column }) => {
            settleExpenseBatchDel([row.id]).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
              this.$refs?.pageRef?.refreshList()
            })
          }
        },
        details_mx: {
          click: ({ row, index, column }) => {
            this.formData = {
              ...row,
              ...(() => {
                var obj = {}
                if (!row.workerId1 && row.workerName1) {
                  obj.workerId1 = row.workerName1
                }
                if (!row.workerId2 && row.workerName2) {
                  obj.workerId2 = row.workerName2
                }
                return obj
              })()
            }
            this.formEdit = true
            this.formBool = true
            this.getWorkers()
          }
        }
      })
    },
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    handleClose() {
      this.$data.formData = this.$options.data().formData
      this.formBool = false
      this.formEdit = false
    },
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          settleExpenseSave({ ...this.formData, settleExpenseId: this.collectItem.id }).then(res => {
            this.$message({
              type: 'success',
              message: '保存成功！'
            })
            this.$refs.pageRef.refreshList()
            this.handleClose()
          })
        }
      })
    },
    getWorkers() {
      memberListPageV2({
        pageNum: 1,
        pageSize: -1,
        isGroupByWorkerId: true,
        params: [{ param: 'b.examine_status', compare: '=', value: 'OK' }]
      }).then(res => {
        this.workerList = res.data.records.map(item => {
          var { id, userId, ...data } = item
          return {
            value: userId,
            label: data.nickName,
            data: {
              workerId: userId,
              workerName: data.nickName,
              workerIdcard: data.idCard,
              workerMobile: data.mobile,
              ...data
            }
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.neibuview {
  box-sizing: border-box;
  padding-left: 16px;

  ::v-deep & > .zj-page-fill-scroll {
    box-sizing: border-box;
    padding-right: 16px;

    & > div:nth-child(1) {
      margin-top: 20px;
    }
  }
}
</style>
