<template>
  <template-page v-if="showTable" ref="pageRef" :get-list="[getList, getList1, getList2][pageLevel]"
    :exportList="[undefined, exportList1, exportList2][pageLevel]"
    :options-evens-group="[optionsEvensGroup0, optionsEvensGroup1, optionsEvensGroup2][pageLevel]"
    :operation="([operation0, operation1, operation2][pageLevel])()"
    :expCode="['', 'workerExp', 'detailExp'][pageLevel]" :table-attributes="tableAttributes" :table-events="tableEvents"
    :moreParameters="moreParameters" :column-parsing="columnParsing">
    <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">
              <el-button size="mini" @click="handleClose">取 消</el-button>
              <el-button 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 {
  settleExpenseList,
  settleExpenseListExport,
  settleMonthWagesGatherList,
  settleMonthWagesList,
  settleMonthWagesListExport,
  settleMonthWagesBatchReject,
  settleMonthWagesBatchSend,
  settleMonthWagesWorkerBatchSend
} from "@/api/costPerDimension";
import { tableDataParsing } from "@/utils/common.js"
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,
      monthItem: {},
      workerItem: {},
      formData: {
        sendDate: "",
        fileUrl: [],
        remark: ""
      },
      formBool: false,
      evaluationColumns: [],
      evaluationData: []
    }
  },
  computed: {
    optionsEvensGroup0() {
      return [
        [
          [
            this.optionsEvensAuth("monthBatchRelease", {
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.warning('请勾选工单')
                  return
                }
                this.getTableJieGou()
                this.formBool = true
              }
            })
          ],
          [
            this.optionsEvensAuth("monthBatchRejection", {
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.warning('请勾选工单')
                  return
                }
                this.$confirm('是否确定驳回', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  settleMonthWagesBatchReject(this.recordSelected.map(item => item.id)).then(res => {
                    this.$message({
                      type: 'success',
                      message: '操作成功！'
                    })
                    this.$refs?.pageRef?.refreshList()
                  })
                }).catch(() => {

                });
              }
            })
          ],
        ]
      ]
    },
    optionsEvensGroup1() {
      return [
        [
          [
            {
              name: "返回月度汇总页面",
              click: () => {
                this.pageLevel = 0
              }
            }
          ],
        ],
        [
          [
            this.optionsEvensAuth("workerBatchRelease", {
              click: () => {
                if (this.recordSelected.length === 0) {
                  this.$message.warning('请勾选工单')
                  return
                }
                this.getTableJieGou()
                this.formBool = true
              }
            })
          ],
        ]
      ]
    },
    optionsEvensGroup2() {
      return [
        [
          [
            {
              name: "返回师傅汇总页面",
              click: () => {
                this.pageLevel = 1
              }
            }
          ],
        ],
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [{
        name: 'el-date-picker',
        md: 6,
        attributes: {
          type: "date",
          'value-format': 'yyyy-MM-dd HH:mm:ss',
        },
        formItemAttributes: {
          label: '发放日期',
          prop: 'sendDate',
          rules: [...required]
        }
      }, {
        md: 24,
        name: 'slot-component',
        formItemAttributes: {
          label: '发放凭证',
          prop: 'fileUrl',
          rules: []
        },
        attributes: {},
        render: (h, { props, onInput }) => {
          return (
            <ImageUpload fileList={this.formData.fileUrl} limit={1} fileType={["image"]} />
          )
        }
      }, {
        name: 'el-input',
        md: 24,
        attributes: {},
        formItemAttributes: {
          label: '备注',
          prop: 'remark',
          rules: []
        }
      }, {
        md: 24,
        name: 'slot-component',
        attributes: {},
        formItemAttributes: {
          label: '',
          'label-width': '0px',
          prop: '',
        },
        render: (h, { props, onInput }) => {
          return <hr />
        }
      }, {
        md: 6,
        name: 'slot-component',
        attributes: {},
        formItemAttributes: {
          label: '结算金额合计',
          prop: '',
        },
        render: (h, { props, onInput }) => {
          return <div>{this.evaluationData.map(item => Number(item.settleAmount)).reduce((accumulator, currentValue) => accumulator + currentValue, 0)}</div>
        }
      }, {
        md: 6,
        name: 'slot-component',
        attributes: {},
        formItemAttributes: {
          label: '发放人数',
          prop: '',
        },
        render: (h, { props, onInput }) => {
          return <div>{this.pageLevel ? this.evaluationData.length : this.evaluationData.map(item => Number(item.settleByCount)).reduce((accumulator, currentValue) => accumulator + currentValue, 0)}</div>
        }
      }, {
        md: 24,
        name: 'slot-component',
        attributes: {},
        formItemAttributes: {
          label: '',
          'label-width': '0px',
          prop: '',
        },
        render: (h, { props, onInput }) => {
          return <zj-table
            columns={this.evaluationColumns}
            table-data={this.evaluationData}
          />
        }
      }]
    }
  },
  watch: {
    pageLevel() {
      this.showTable = false
      this.$nextTick(() => {
        this.showTable = true
      })
    }
  },
  methods: {
    getList: settleMonthWagesGatherList,
    getList1(p, cb) {
      var pam = JSON.parse(JSON.stringify(p))
      try {
        pam.params.push({ "param": "a.settle_month_wages_id", "compare": "=", "value": this.monthItem.id })
        cb && cb(pam)
        return settleMonthWagesList(pam)
      } catch (err) {
      }
    },
    exportList1: settleMonthWagesListExport,
    getList2(p, cb) {
      var pam = JSON.parse(JSON.stringify(p))
      try {
        pam.params.push(
          { "param": "a.settle_month_wages_id", "compare": "=", "value": this.monthItem.id },
          { "param": "month_settle_worker_id", "compare": "=", "value": this.workerItem.workerId }
        )
        cb && cb(pam)
        return settleExpenseList(pam)
      } catch (err) {
      }
    },
    exportList2: settleExpenseListExport,
    selectable(row, index) {
      return !["END"].includes(Object.entries(row.selectMapData.status).find(([key, val]) => val == row.status)?.[0])
    },
    operation0() {
      return this.operationBtn({
        monthRelease: {
          conditions: ({ row, index, column }) => {
            return row.status != "END"
          },
          click: ({ row, index, column }) => {
            this.recordSelected = [{ ...row }]
            this.getTableJieGou()
            this.formBool = true
          }
        },
        monthRejection: {
          prompt: "是否确定驳回?",
          conditions: ({ row, index, column }) => {
            return row.status == "NOT"
          },
          click: ({ row, index, column }) => {
            settleMonthWagesBatchReject([row.id]).then(res => {
              this.$message({
                type: 'success',
                message: '操作成功！'
              })
              this.$refs?.pageRef?.refreshList()
            })
          }
        },
        monthDetails: {
          click: ({ row, index, column }) => {
            this.monthItem = row
            this.pageLevel = 1
          }
        }
      })
    },
    operation1() {
      return this.operationBtn({
        workerRelease: {
          conditions: ({ row, index, column }) => {
            return row.status != "END"
          },
          click: ({ row, index, column }) => {
            this.recordSelected = [{ ...row }]
            this.getTableJieGou()
            this.formBool = true
          }
        },
        workerDetails: {
          click: ({ row, index, column }) => {
            this.workerItem = row
            this.pageLevel = 2
          }
        },
      })
    },
    operation2() {
      return undefined
    },
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    handleClose() {
      this.recordSelected = []
      this.evaluationColumns = []
      this.evaluationColumns = []
      this.$refs?.pageRef?.refreshList()
      this.$data.formData = this.$options.data().formData
      this.formBool = false
    },
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          ; ([settleMonthWagesBatchSend, settleMonthWagesWorkerBatchSend][this.pageLevel])({
            ...this.formData,
            fileUrl: this.formData.fileUrl.length ? this.formData.fileUrl[0]?.url : "",
            ids: this.recordSelected.map(item => item.id),
            settleMonthWagesId: this.monthItem.id || undefined
          }).then(res => {
            this.$message({
              type: 'success',
              message: '发放成功！'
            })
            this.handleClose()
          })
        }
      })
    },
    getTableJieGou() {
      ; (([settleMonthWagesGatherList, settleMonthWagesList])[this.pageLevel])({ "pageNum": 1, "pageSize": 1, "params": [] }).then(res => {
        this.evaluationColumns = tableDataParsing(res.fieldBeans.filter(item => !~(([["aaa"], ["id", "settleMonthWagesId", "settleMonthWagesDetailId", "workerId"]])[this.pageLevel]).indexOf(item.jname))).map(item => {
          return item
        })
        this.$nextTick(() => {
          this.evaluationData = this.recordSelected.map(item => {
            Object.keys(item).map(key => {
              var val = JSON.parse(res?.fieldBeans?.find(val => val.jname == key)?.enumMap || "{}")[item[key]];
              if (val) item[key] = val;
            })
            return item
          })
        })
      })
    }
  }
}
</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>
