<template>
  <template-page
    v-if="pageShow"
    ref="pageRef"
    :get-list="getList"
    :exportList="exportList"
    :table-attributes="tableAttributes"
    :table-events="tableEvents"
    :options-evens-group="optionsEvensGroup"
    :moreParameters="moreParameters"
    :column-parsing="columnParsing"
    :operation="operation()"
    key="pageType"
  >
    <div class="cartographer_big aaaaaaaaaaaaaaa">
      <el-dialog title="新增" width="100%" :modal="false" :visible.sync="formDialog" :before-close="handleClose">
        <zj-page-container>
          <zj-page-fill>
            <div style="box-sizing: border-box; padding: 20px 20px 0 20px" v-if="formDialog">
              <zj-form-container ref="formRef" :form-data="formData" :form-attributes="{ size: 'mini' }">
                <zj-form-module title="新增" label-width="110px" :form-data="formData" :form-items="formItems">
                </zj-form-module>
                <zj-form-module title="师傅信息" :form-data="formData" :form-items="items2"> </zj-form-module>
              </zj-form-container>
            </div>
          </zj-page-fill>
          <div style="text-align: right; box-sizing: border-box; padding: 16px 20px">
            <el-button size="mini" @click="handleClose">取消</el-button>
            <el-button size="mini" type="primary" @click="save">保存</el-button>
          </div>
        </zj-page-container>
      </el-dialog>
    </div>
    <div class="cartographer_big aaaaaaaaaaaaaaa">
      <el-dialog title="详情" width="100%" :modal="false" :visible.sync="formDialog2" :before-close="handleClose">
        <zj-page-container>
          <zj-page-fill>
            <div style="box-sizing: border-box; padding: 20px 20px 0 20px" v-if="formDialog2">
              <zj-form-container ref="formRef2" :form-data="formData" :form-attributes="{ size: 'mini' }">
                <zj-form-module title="详情" label-width="110px" :form-data="formData" :form-items="formItems3">
                </zj-form-module>
                <zj-form-module title="缴费记录" label-width="110px" :form-data="formData" :form-items="formItems4">
                </zj-form-module>
                <zj-form-module title="退款记录" label-width="110px" :form-data="formData" :form-items="formItems5">
                </zj-form-module>
              </zj-form-container>
            </div>
          </zj-page-fill>
          <div style="text-align: right; box-sizing: border-box; padding: 16px 20px">
            <el-button size="mini" @click="handleClose">取消</el-button>
          </div>
        </zj-page-container>
      </el-dialog>
    </div>

    <div class="cartographer_big aaaaaaaaaaaaaaa">
      <el-dialog title="退款申请" width="100%" :modal="false" :visible.sync="formDialog3" :before-close="handleClose">
        <zj-page-container>
          <zj-page-fill>
            <div style="box-sizing: border-box; padding: 20px 20px 0 20px" v-if="formDialog3">
              <zj-form-container ref="formRef3" :form-data="formTK" :form-attributes="{ size: 'mini' }">
                <zj-form-module title="详情" label-width="110px" :form-data="formData" :form-items="formItems3">
                </zj-form-module>
                <zj-form-module title="缴费记录" label-width="110px" :form-data="formData" :form-items="formItems4">
                </zj-form-module>
                <zj-form-module title="退款记录" label-width="110px" :form-data="formData" :form-items="formItems5">
                </zj-form-module>
                <zj-form-module title="退款记录" label-width="110px" :form-data="formTK" :form-items="formItems6">
                </zj-form-module>
              </zj-form-container>
            </div>
          </zj-page-fill>
          <div style="text-align: right; box-sizing: border-box; padding: 16px 20px">
            <el-button size="mini" @click="handleClose">取 消</el-button>
            <el-button size="mini" type="primary" @click="queding">确 定</el-button>
          </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 pagingTransfer from '@/components/paging-transfer.vue'
import {
  workerWarrantyList,
  workerWarrantyListExport,
  workerWarrantyImport,
  workerWarrantyAdd,
  workerWarrantyRefund,
  workerWarrantyDetail
} from '@/api/qualityGuaranteeFund.js'
import { commonTemplateDownload } from '@/api/common.js'
import { required } from '@/components/template/rules_verify.js'
import { memberListPageV2 } from '@/api/masterManagement'
import { EventBus } from '@/utils/eventBus'
import ImageUpload from '@/components/file-upload'
export default {
  components: { TemplatePage },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      pageType: 'list',
      pageShow: true,
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialog: false,
      formDialog2: false,
      formDialog3: false,
      formData: {
        shouldAmount: '',
        everyAmount: '',
        websitUserId: '',
        worker: []
      },
      formInline: {
        websitId: '',
        websitName: '',
        workerNumber: '',
        nickName: '',
        mobile: '',
        idCard: ''
      },
      formTK: {
        fileUrl: [],
        refundAmount: '',
        refundTime: '',
        remark: '',
        warrantyId: '',
        ktkje: ''
      }
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: this.openForm
            })
          ]
        ],
        [
          [
            this.optionsEvensAuth('listImport', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(workerWarrantyImport, moduleName)
                }
              }
            })
          ],
          [
            this.optionsEvensAuth('downloadTemplate1', {
              click: () => {
                commonTemplateDownload({ name: '质保金新增模板.xlsx' }, `质保金新增模板`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            })
          ]
        ],
        [
          [
            this.optionsEvensAuth('payFeesImport', ({ moduleName }) => {
              return {
                name: moduleName,
                render: () => {
                  return this.importButton(workerWarrantyImport, moduleName)
                }
              }
            })
          ],
          [
            this.optionsEvensAuth('downloadTemplate2', {
              click: () => {
                commonTemplateDownload({ name: '质保金缴费模板.xlsx' }, `质保金缴费模板`)
                  .then(res => {
                    this.$message({
                      message: '下载成功',
                      type: 'success'
                    })
                  })
                  .catch(err => {
                    this.$message.error('下载失败')
                  })
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [
        {
          name: 'el-input',
          md: 8,
          attributes: {
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '质保金总金额',
            prop: 'shouldAmount',
            rules: [...required]
          }
        },
        {
          name: 'el-input',
          md: 8,
          attributes: {
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '每期扣款金额',
            prop: 'everyAmount',
            rules: [...required]
          }
        }
      ]
    },
    items2() {
      return [
        {
          name: 'slot-component',
          md: 24,
          attributes: {},
          formItemAttributes: { label: '', 'label-width': '0px', prop: 'worker', rules: [] },
          render: (h, { props, onInput }) => {
            var { formData } = props
            return (
              <div>
                <div>
                  <el-form
                    size="mini"
                    inline={true}
                    value={this.formInline}
                    onInput={v => {
                      this.formInline = v
                    }}
                    label-width="0px"
                  >
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.websitId}
                        onInput={v => {
                          this.formInline.websitId = v
                        }}
                        placeholder="网点编号"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.websitName}
                        onInput={v => {
                          this.formInline.websitName = v
                        }}
                        placeholder="网点名称"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.workerNumber}
                        onInput={v => {
                          this.formInline.workerNumber = v
                        }}
                        placeholder="师傅编号"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.nickName}
                        onInput={v => {
                          this.formInline.nickName = v
                        }}
                        placeholder="师傅名称"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.mobile}
                        onInput={v => {
                          this.formInline.mobile = v
                        }}
                        placeholder="师傅手机号"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="">
                      <el-input
                        value={this.formInline.idCard}
                        onInput={v => {
                          this.formInline.idCard = v
                        }}
                        placeholder="师傅身份证"
                      ></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        type="primary"
                        onClick={() => {
                          EventBus.$emit('handlePaginationCallBaXXXXX')
                        }}
                      >
                        查询
                      </el-button>
                      <el-button
                        onClick={() => {
                          this.formInline.websitId = ''
                          this.formInline.websitName = ''
                          this.formInline.workerNumber = ''
                          this.formInline.nickName = ''
                          this.formInline.mobile = ''
                          this.formInline.idCard = ''
                          this.$nextTick(() => {
                            EventBus.$emit('handlePaginationCallBaXXXXX')
                          })
                        }}
                      >
                        重置
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
                <pagingTransfer
                  handlePaginationCallBackKey="handlePaginationCallBaXXXXX"
                  value={this.formData.worker}
                  onInput={v => {
                    this.formData.worker = v
                  }}
                  left-columns={[
                    { id: 'websitNameLabel', label: '所属网点', width: '160' },
                    { id: 'nickName', label: '师傅名称', width: '160' },
                    { id: 'workerNumber', label: '师傅编号', width: '160' },
                    { id: 'mobile', label: '师傅手机号', width: '160' },
                    { id: 'idCard', label: '师傅身份证号', width: '160' }
                  ]}
                  right-columns={[
                    { id: 'websitNameLabel', label: '所属网点', width: '160' },
                    { id: 'nickName', label: '师傅名称', width: '160' },
                    { id: 'workerNumber', label: '师傅编号', width: '160' },
                    { id: 'mobile', label: '师傅手机号', width: '160' },
                    { id: 'idCard', label: '师傅身份证号', width: '160' }
                  ]}
                  pagination-call-back={this.paginationCallback}
                  title-texts={['待选项', '已选项']}
                  min-height="300px"
                  table-row-key={row => row.id}
                />
              </div>
            )
          }
        }
      ]
    },
    formItems3() {
      return [
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '网点编号',
            prop: 'websitId'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '网点名称',
            prop: 'websitName'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '师傅编号',
            prop: 'workerNumber'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '师傅姓名',
            prop: 'workerName'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '手机号码',
            prop: 'mobile'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '身份证',
            prop: 'idCard'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '入职时间',
            prop: 'inTime'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '离职时间',
            prop: 'outTime'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '应缴纳金额',
            prop: 'shouldAmount'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '已缴纳金额',
            prop: 'payableAmount'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '待缴纳金额',
            prop: 'waitAmount'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '已缴纳期数',
            prop: 'payableNum'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '创建人',
            prop: 'createBy'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '创建时间',
            prop: 'createTime'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '最后修改人',
            prop: 'updateBy'
          }
        },
        {
          name: 'el-input',
          md: 6,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '最后修改时间',
            prop: 'updateTime'
          }
        }
      ]
    },
    formItems4() {
      return [
        {
          name: 'slot-component',
          md: 24,
          attributes: {},
          formItemAttributes: { label: '', 'label-width': '0px', prop: 'worker', rules: [] },
          render: (h, { props, onInput }) => {
            var { formData } = props
            return (
              <div>
                <zj-table
                  columns={[
                    {
                      columnAttributes: {
                        label: '缴费时间',
                        prop: 'payTime'
                      }
                    },
                    {
                      columnAttributes: {
                        label: '缴费金额',
                        prop: 'payAmount'
                      }
                    }
                  ]}
                  tableData={formData.workerWarrantyPays}
                  tableAttributes={{
                    size: 'mini',
                    border: true
                  }}
                />
              </div>
            )
          }
        }
      ]
    },
    formItems5() {
      return [
        {
          name: 'slot-component',
          md: 24,
          attributes: {},
          formItemAttributes: { label: '', 'label-width': '0px', prop: 'worker', rules: [] },
          render: (h, { props, onInput }) => {
            var { formData } = props
            return (
              <div>
                <zj-table
                  columns={[
                    {
                      columnAttributes: {
                        label: '退款金额',
                        prop: 'refundAmount'
                      }
                    },
                    {
                      columnAttributes: {
                        label: '退款凭证',
                        prop: 'fileUrl'
                      },
                      render: (h, { row, column, index }) => {
                        return row.fileUrl ? (
                          <div class="redbordererr">
                            {row.fileUrl.split(',').map(url => (
                              <el-image
                                style="width: 100px; height: 100px"
                                src={this.$showImgUrl(url)}
                                preview-src-list={[this.$showImgUrl(url)]}
                              ></el-image>
                            ))}
                          </div>
                        ) : null
                      }
                    },
                    {
                      columnAttributes: {
                        label: '退款人',
                        prop: 'createBy'
                      }
                    },
                    {
                      columnAttributes: {
                        label: '退款时间',
                        prop: 'refundTime'
                      }
                    },
                    {
                      columnAttributes: {
                        label: '说明',
                        prop: 'remark'
                      }
                    }
                  ]}
                  tableData={formData.workerWarrantyRefunds}
                  tableAttributes={{
                    size: 'mini',
                    border: true
                  }}
                />
              </div>
            )
          }
        }
      ]
    },
    formItems6() {
      return [
        {
          name: 'el-input',
          md: 8,
          attributes: {
            disabled: true,
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '可退金额',
            prop: 'ktkje'
          }
        },
        {
          name: 'el-input',
          md: 8,
          attributes: {
            placeholder: '请输入'
          },
          formItemAttributes: {
            label: '退款金额',
            prop: 'refundAmount',
            rules: [...required]
          }
        },
        {
          name: 'el-date-picker',
          md: 8,
          attributes: {
            placeholder: '请输入',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime'
          },
          formItemAttributes: {
            label: '退款时间',
            prop: 'refundTime',
            rules: [...required]
          }
        },
        {
          md: 24,
          isShow: true,
          name: 'slot-component',
          formItemAttributes: {
            label: '收款凭证',
            prop: 'fileUrl',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return <ImageUpload fileList={this.formTK.fileUrl} limit={9} />
          }
        },
        {
          md: 24,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入备注内容', type: 'textarea', rows: 5 },
          formItemAttributes: {
            label: '说明',
            prop: 'remark',
            rules: []
          }
        }
      ]
    }
  },
  methods: {
    // 列表请求函数
    getList: workerWarrantyList,
    // 列表导出函数
    exportList: workerWarrantyListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 打开创建弹窗
    openForm() {
      this.formDialog = true
    },
    handleClose() {
      this.$refs?.formRef?.resetFields()
      this.$data.formInline = this.$options.data().formInline
      this.$data.formData = this.$options.data().formData
      this.$data.formTK = this.$options.data().formTK
      this.formDialog = false
      this.formDialog2 = false
      this.formDialog3 = false
    },
    // 操作按钮
    operation() {
      return this.operationBtn({
        details: {
          click: ({ row, index, column }) => {
            workerWarrantyDetail({ warrantyId: row.warrantyId }).then(res => {
              this.formData = {
                ...res.data,
                inTime: res.data.inTime ? res.data.inTime?.split(' ')?.[0] : '',
                workerWarrantyPays: res.data.workerWarrantyPays?.map(item => {
                  return {
                    ...item,
                    payTime: item.payTime ? item.payTime?.split(' ')?.[0] : ''
                  }
                })
              }
              this.formDialog2 = true
            })
          }
        },
        refund: {
          conditions: ({ row, index, column }) => {
            return (row.payableAmount || 0) - (row.refundAmount || 0) > 0
          },
          click: ({ row, index, column }) => {
            workerWarrantyDetail({ warrantyId: row.warrantyId }).then(res => {
              this.formData = {
                ...res.data,
                inTime: res.data.inTime ? res.data.inTime?.split(' ')?.[0] : '',
                workerWarrantyPays: res.data.workerWarrantyPays?.map(item => {
                  return {
                    ...item,
                    payTime: item.payTime ? item.payTime?.split(' ')?.[0] : ''
                  }
                })
              }
              this.formTK.ktkje = (row.payableAmount || 0) - (row.refundAmount || 0)
              this.formDialog3 = true
            })
          }
        }
      })
    },
    queding() {
      this.$refs.formRef3.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          if (this.formTK.refundAmount <= 0) {
            this.$message.warning('退款金额必须大于0！')
            return
          }
          workerWarrantyRefund({
            ...this.formTK,
            warrantyId: this.formData.warrantyId,
            fileUrl: this.formTK.fileUrl.map(item => item.url).join(',')
          }).then(res => {
            this.$message({
              type: 'success',
              message: '新增成功'
            })
            this.handleClose()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    // 保存
    save() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          if (this.formData.worker.length == 0) {
            this.$message.warning('师傅必须至少选择一个！')
            return
          }
          workerWarrantyAdd({
            ...this.formData,
            websitUserId: this.formData.worker.map(item => item.id).join(',')
          }).then(res => {
            this.$message({
              type: 'success',
              message: '新增成功'
            })
            this.handleClose()
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    paginationCallback({ pageIndex, pageSize }) {
      return new Promise(resolve => {
        memberListPageV2({
          pageNum: pageIndex,
          pageSize: pageSize,
          params: [
            ...(() => {
              if (this.formInline.websitId) {
                return [{ param: 'b.websit_id', compare: 'like', value: this.formInline.websitId }]
              }
              return []
            })(),
            ...(() => {
              if (this.formInline.websitName) {
                return [{ param: 'c.name', compare: 'like', value: this.formInline.websitName }]
              }
              return []
            })(),
            ...(() => {
              if (this.formInline.workerNumber) {
                return [{ param: 'a.worker_number', compare: 'like', value: this.formInline.workerNumber }]
              }
              return []
            })(),
            ...(() => {
              if (this.formInline.nickName) {
                return [{ param: 'a.nick_name', compare: 'like', value: this.formInline.nickName }]
              }
              return []
            })(),
            ...(() => {
              if (this.formInline.mobile) {
                return [{ param: 'a.mobile', compare: 'like', value: this.formInline.mobile }]
              }
              return []
            })(),
            ...(() => {
              if (this.formInline.idCard) {
                return [{ param: 'a.id_card', compare: 'like', value: this.formInline.idCard }]
              }
              return []
            })(),
            { param: 'b.examine_status', compare: '=', value: 'OK' },
            { param: 'c.attr', compare: '=', value: 'SELF' }
          ]
        }).then(res => {
          resolve({
            total: res.data.total,
            data: res.data.records.map(item => ({
              ...item,
              websitNameLabel: `(${item.websitId})${item.websitName}`
            }))
          })
        })
      })
    }
  }
}
</script>

<style lang="scss">
.aaaaaaaaaaaaaaa {
  .cell {
    text-align: left !important;
  }
}
</style>
