<template>
  <div class="withinLine">
    <el-button type="primary" size="mini" @click="open">{{ resultCodeName }}</el-button>
    <el-dialog
      title=""
      width="750px"
      custom-class="diy-dialog"
      append-to-body
      :modal="true"
      :visible.sync="formDialog"
      :show-close="true"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :before-close="formCancel"
    >
      <zj-form-container v-if="formDialog" ref="formRef" :form-data="formData" :styleSwitch="false">
        <zj-form-module
          :title="resultCodeName"
          label-width="140px"
          :showPackUp="false"
          :form-data="formData"
          :form-items="formItems"
        >
        </zj-form-module>
      </zj-form-container>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="formCancel">取 消</el-button>
        <el-button size="mini" :disabled="disabled" @click="formConfirm" type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import buttonMixin from './button_mixin.js'
import ImageUpload from '@/components/file-upload'
import { required } from '@/components/template/rules_verify.js'
import { orderBaseLogAdd } from '@/api/workOrderPool.js'
import editTable from '@/components/template/editTable.js'
import { abnormalList } from '@/api/abnormalFeedbackConfig'
export default {
  mixins: [buttonMixin, editTable],
  components: {
    ImageUpload
  },
  props: {
    resultCode: {
      type: String,
      default: ''
    },
    resultCodeName: {
      type: String,
      default: '过程反馈'
    }
  },
  data() {
    return {
      type: this.resultCode
        ? [this.resultCode]
        : ['备注', '预约', '改约', '异常反馈', '完工反馈', '回访', '待件', '拉修', '不接电话', '延误', '质量信息'],
      formDialog: false,
      formData: {
        orderBaseId: this.orderInfo.id,
        imgSrc: [],
        content: '',
        appointmentTime: '',
        appointmentEndTime: '',
        type: this.resultCode,
        typeText: this.resultCode,
        daijianItems: [],
        exType: '',
        exNote: '',
        ywType: '',
        zlNumber: '',
        fkTime: ''
      },
      formRules: {},
      abnormalListLists: []
    }
  },
  computed: {
    // 用户信息
    userInfo() {
      return JSON.parse(localStorage.getItem('greemall_user'))
    },
    formItems() {
      return [
        {
          md: 24,
          name: 'el-radio',
          options: this.type.map(item => ({ label: item, value: item })),
          attributes: {},
          formItemAttributes: {
            label: '反馈结果',
            prop: 'type',
            rules: [...required]
          },
          events: {
            change: val => {
              this.formData.typeText = this.formData.type
              this.formData.daijianItems = []
              this.isEditTableIndex = -1
            }
          }
        },
        {
          isShow: !!~['异常反馈'].indexOf(this.formData.type),
          md: 24,
          name: 'el-radio',
          options: [...new Set(this.abnormalListLists.map(item => item.exType))].map(v => ({ label: v, value: v })),
          attributes: {},
          formItemAttributes: {
            label: '异常类型',
            prop: 'exType',
            rules: [...required]
          },
          events: {
            change: () => {
              this.formData.exNote = ''
            }
          }
        },
        {
          isShow: !!~['异常反馈'].indexOf(this.formData.type),
          md: 24,
          name: 'el-radio',
          options: this.abnormalListLists
            .filter(item => item.exType === this.formData.exType)
            .map(v => ({ label: v.exNote, value: v.exNote })),
          attributes: {},
          formItemAttributes: {
            label: '异常原因',
            prop: 'exNote',
            rules: [...required]
          }
        },
        {
          isShow: !!~['延误'].indexOf(this.formData.type),
          md: 24,
          name: 'el-radio',
          options: [
            { label: '无人接听', value: '无人接听' },
            { label: '天气原因', value: '天气原因' },
            { label: '配件未到货', value: '配件未到货' },
            { label: '异常工单', value: '异常工单' }
          ],
          attributes: {},
          formItemAttributes: {
            label: '延误类型',
            prop: 'ywType',
            rules: [...required]
          }
        },

        {
          isShow: !!~['质量信息'].indexOf(this.formData.type),
          md: 12,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '质量反馈编号',
            prop: 'zlNumber',
            rules: [...required]
          }
        },

        {
          isShow: !!~['质量信息'].indexOf(this.formData.type),
          md: 12,
          name: 'el-date-picker',
          attributes: { placeholder: '请输入', type: 'datetime', 'value-format': 'yyyy-MM-dd HH:mm:ss' },
          formItemAttributes: {
            label: '反馈日期',
            prop: 'fkTime',
            rules: [...required]
          }
        },

        {
          isShow: !!~['预约', '改约', '待件', '拉修', '不接电话', '延误'].indexOf(this.formData.type),
          name: 'el-date-picker',
          md: 12,
          attributes: {
            'picker-options': 'pickerOptions11',
            'popper-class': 'custom-popper11',
            'append-to-body': true,
            style: { width: '100%' },
            type: 'datetime',
            placeholder: '请选择',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            'picker-options': {
              disabledDate: time => {
                return time.getTime() < Date.now() - 86400000
              }
            }
          },
          events: {
            change: value => {
              if (value && new Date(value).getTime() < new Date().getTime() - 2000) {
                this.formData.appointmentTime = ''
                this.$message.warning('必须大于当前时间')
              } else {
                this.formData.appointmentEndTime = ''
              }
            }
          },
          formItemAttributes: {
            label: `${
              !!~['改约', '待件', '拉修', '不接电话', '延误'].indexOf(this.formData.type) ? '改约' : '预约'
            }上门开始时间`,
            prop: 'appointmentTime',
            rules: [...required]
          }
        },

        {
          isShow: !!~['预约', '改约', '待件', '拉修', '不接电话', '延误'].indexOf(this.formData.type),
          name: 'el-date-picker',
          md: 12,
          attributes: {
            'picker-options': 'pickerOptions11',
            'popper-class': 'custom-popper11',
            'append-to-body': true,
            style: { width: '100%' },
            type: 'datetime',
            placeholder: '请选择',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            'picker-options': {
              disabledDate: time => {
                var data = this.formData?.appointmentTime?.split(' ')?.[0]
                return (
                  time.getTime() < new Date(data ? `${data} 00:00:00` : '').getTime() ||
                  time.getTime() > new Date(data ? `${data} 00:00:00` : '').getTime()
                )
              }
            }
          },
          events: {
            change: value => {
              if (value && new Date(value).getTime() < new Date().getTime() - 2000) {
                this.formData.appointmentEndTime = ''
                this.$message.warning('必须大于当前时间')
              } else if (value && new Date(value).getTime() < new Date(this.formData?.appointmentTime).getTime()) {
                this.formData.appointmentTime = value
              }
            }
          },
          formItemAttributes: {
            label: `${
              !!~['改约', '待件', '拉修', '不接电话', '延误'].indexOf(this.formData.type) ? '改约' : '预约'
            }上门结束时间`,
            prop: 'appointmentEndTime',
            rules: [...required]
          }
        },

        {
          isShow: !!~['待件'].indexOf(this.formData.type),
          name: 'slot-component',
          md: 24,
          attributes: { disabled: false, placeholder: '' },
          formItemAttributes: {
            label: '待件明细',
            prop: 'daijianItems',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return this.convertTableJson(
              value,
              [
                {
                  columnAttributes: {
                    label: '待件申请编号',
                    prop: 'applyNum1',
                    rules: [...required]
                  },
                  editRender: this.inputEditRender,
                  viewRender: this.inputViewRender
                },
                {
                  columnAttributes: {
                    label: '待件物料编号',
                    prop: 'applyNum2',
                    rules: [...required]
                  },
                  editRender: this.inputEditRender,
                  viewRender: this.inputViewRender
                }
              ],
              {
                isEdit: true,
                isAdd: true,
                isDel: true
              },
              {
                add: () => {
                  this.formData.daijianItems.push({
                    applyNum1: '',
                    applyNum2: ''
                  })
                  this.isEditTableIndex = this.formData.daijianItems.length - 1
                },
                delete: ({ row, column, index }, cb) => {
                  if (this.isEditTableIndex == index) {
                    this.isEditTableIndex = -1
                  } else if (this.isEditTableIndex > index) {
                    this.isEditTableIndex--
                  }
                  cb?.()
                },
                verify: ({ row, column, index }, isEditTableIndex) => {
                  return new Promise(r => {
                    if (isEditTableIndex > -1) {
                      this.$refs.formRef.validateField(
                        [`daijianItems.${isEditTableIndex}.applyNum1`, `daijianItems.${isEditTableIndex}.applyNum2`],
                        v => {
                          r(!!v)
                        }
                      )
                    } else {
                      r(true)
                    }
                  })
                }
              }
            )
          }
        },

        {
          md: 24,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'textarea' },
          formItemAttributes: {
            label: '反馈内容',
            prop: 'content',
            rules: [...required]
          }
        },

        {
          md: 24,
          name: 'slot-component',
          formItemAttributes: {
            label: '上传附件(最多6个)',
            prop: 'imgSrc',
            rules: []
          },
          render: (h, { props, onInput }) => {
            return <ImageUpload fileList={this.formData.imgSrc} limit={6} />
          }
        }
      ]
    }
  },
  methods: {
    open() {
      Promise.all([
        abnormalList({ pageNum: 1, pageSize: -1, params: [{ param: 'status', compare: '=', value: 'ON' }] })
      ]).then(([res1]) => {
        this.abnormalListLists = res1.data.records
        this.formDialog = true
      })
    },
    formCancel() {
      this.formDialog = false
      this.formData = {
        orderBaseId: this.orderInfo.id,
        imgSrc: [],
        content: '',
        appointmentTime: '',
        appointmentEndTime: '',
        type: this.resultCode,
        typeText: this.resultCode
      }
    },
    formConfirm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.lockBtn()

          orderBaseLogAdd({
            ...this.formData,
            imgSrc: this.formData.imgSrc.map(item => item.url).join(','),
            applyNum: !!~['待件'].indexOf(this.formData.type)
              ? this.formData.daijianItems.map(item => `${item.applyNum1}|${item.applyNum2}`).join(',')
              : ''
          })
            .then(res => {
              this.unlockBtn()
              // 编辑保存后不跳转列表，刷新数据
              this.acquireVerify(this, 'getorderDetail')()
              // 刷新操作记录
              this.acquireVerify(this, 'getOrderBaseLogList')()
              this.$message({
                type: 'success',
                message: '反馈成功'
              })
              this.formCancel()
            })
            .catch(() => {
              this.unlockBtn()
            })
        }
      })
    },

    inputEditRender: (h, { row, column, index }) => {
      return (
        <div class="redbordererr">
          <el-form-item
            label=""
            label-width="0px"
            prop={`daijianItems.${index}.${column.columnAttributes.prop}`}
            rules={column.columnAttributes.rules || []}
          >
            <el-input
              value={row[column.columnAttributes.prop]}
              onInput={val => {
                row[column.columnAttributes.prop] = val
              }}
              placeholder="请输入内容"
            ></el-input>
          </el-form-item>
        </div>
      )
    },

    inputViewRender: (h, { row, column, index }) => {
      return <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.xijiezhanshi {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.withinLine {
  display: inline-block;

  ::v-deep .el-button {
    margin-left: 0;
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>
