<template>
  <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]">
    <template slot-scope="{ activeKey, data }">
      <template-page
        v-if="activeKey == 'list'"
        ref="pageRef"
        :get-list="getList"
        :table-attributes="tableAttributes"
        :table-events="tableEvents"
        :options-evens-group="optionsEvensGroup"
        :moreParameters="moreParameters"
        :column-parsing="columnParsing"
        :operation="operation()"
        :exportList="exportList"
        :operationColumnWidth="80"
      >
      </template-page>
      <div v-if="~['add', 'edit', 'detail'].indexOf(activeKey)">
        <zj-form-container ref="formRef" :form-data="formData" :styleSwitch="false">
          <zj-form-module
            title=""
            label-width="110px"
            :showPackUp="false"
            :form-data="formData"
            :form-items="formItems"
            :disabled="formDialogType == 2"
          >
          </zj-form-module>
        </zj-form-container>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="data.removeTab()">取 消</el-button>
          <el-button v-if="formDialogType !== 2" size="mini" @click="formConfirm(data.removeTab)" type="primary"
            >确 定</el-button
          >
        </div>
      </div>
    </template>
  </zj-tab-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import ImageUpload from '@/components/file-upload'
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
import { listPageV2, pageExport, getDetail, add, edit, del, getExamine } from '@/api/workOrder/rewardsPunishmentsOrder'
import { getWebsit } from '@/api/customerManagement'
import { getWorker } from '@/api/auxiliaryFittings/auxiliarySalesOrder'
import operation_mixin from '@/components/template/operation_mixin.js'
export default {
  components: { TemplatePage, ImageUpload },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ['新增', '编辑', '详情'],
      formDialog: false,
      type: JSON.parse(localStorage.getItem('greemall_user')).type, //type=1商户, type=0网点
      formData: {
        companyName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
        websit: {},
        websitName: '',
        websitId: '',
        worker: {},
        workerId: '',
        workerName: '',
        mobile: '',
        idcard: '',
        examineProjectName: '',
        examineProjectId: '',
        examineProjectType: '',
        examineProjectAmount: '',
        examineProject: {},
        orderBaseId: '',
        fileUrl: [],
        remark: ''
      },
      websitList: [],
      workerList: [],
      examineList: [],
      formType: 'add',
      formVisible: false
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openForm('add')
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', disabled: true },
          formItemAttributes: {
            label: '所属商户',
            prop: 'companyName',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: this.type == 1,
          name: 'slot-component',
          attributes: { placeholder: '请输入网点名称' },
          formItemAttributes: {
            label: '网点名称',
            prop: 'websitId',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <el-select
                v-model={this.formData.websit}
                disabled={this.formDialogType != 0}
                value-key="websitId"
                onChange={e => {
                  this.formData.websitId = e.websitId
                  this.formData.websitName = e.name
                  this.formData.worker = {}
                  this.formData.workerId = ''
                  this.formData.workerName = ''
                  this.formData.idcard = ''
                  this.formData.mobile = ''
                  this.getWorker()
                }}
                placeholder="请选择"
                style="width: 100%;"
              >
                {this.websitList.map((item, index) => {
                  return <el-option key={item.websitId} label={item.name} value={item}></el-option>
                })}
              </el-select>
            )
          }
        },
        {
          md: 6,
          isShow: this.type == 0,
          name: 'el-input',
          attributes: { placeholder: '请输入网点名称', disabled: true },
          formItemAttributes: {
            label: '网点名称',
            prop: 'websitName',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'slot-component',
          attributes: { placeholder: '请选择工程师' },
          formItemAttributes: {
            label: '选择工程师',
            prop: 'workerId',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <el-select
                v-model={this.formData.worker}
                disabled={this.formDialogType != 0}
                value-key="nickName"
                onChange={e => {
                  this.formData.workerId = e.userId
                  this.formData.workerName = e.nickName
                  this.formData.idcard = e.idCard
                  this.formData.mobile = e.mobile
                }}
                placeholder="请选择"
                style="width: 100%;"
              >
                {this.workerList.map((item, index) => {
                  return <el-option key={item.userId} label={item.nickName} value={item}></el-option>
                })}
              </el-select>
            )
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '身份证',
            prop: 'idcard',
            rules: this.formData.idcard
              ? [
                  {
                    pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                    message: '身份证号格式不正确',
                    trigger: 'blur'
                  }
                ]
              : []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '联系电话',
            prop: 'mobile',
            rules: this.formData.mobile
              ? [
                  {
                    pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/,
                    message: '电话号码格式不正确',
                    trigger: 'blur'
                  }
                ]
              : []
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'slot-component',
          attributes: { placeholder: '请选择考核项目' },
          formItemAttributes: {
            label: '选择考核项目',
            prop: 'examineProjectName',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <el-select
                v-model={this.formData.examineProject}
                disabled={this.formDialogType != 0}
                value-key="name"
                onChange={e => {
                  this.formData.examineProjectId = e.id
                  this.formData.examineProjectName = e.name
                  this.formData.examineProjectType = e.type
                  this.formData.examineProjectAmount = e.amount
                }}
                placeholder="请选择"
                style="width: 100%;"
              >
                {this.examineList.map((item, index) => {
                  return <el-option key={item.id} label={item.name} value={item}></el-option>
                })}
              </el-select>
            )
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'slot-component',
          attributes: {},
          formItemAttributes: {
            label: '考核类型',
            prop: 'examineProjectType',
            rules: [...required]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <el-radio-group v-model={this.formData.examineProjectType}>
                <el-radio disabled={true} label="REWARD">
                  奖励
                </el-radio>
                <el-radio disabled={true} label="PUNISH">
                  惩罚
                </el-radio>
              </el-radio-group>
            )
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入', type: 'number', disabled: true },
          formItemAttributes: {
            label: '考核金额',
            prop: 'examineProjectAmount',
            rules: [...required]
          }
        },
        {
          md: 6,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '关联工单号',
            prop: 'orderBaseId',
            rules: []
          }
        },
        {
          md: 24,
          isShow: true,
          name: 'slot-component',
          formItemAttributes: {
            label: '附件',
            prop: 'fileUrl',
            rules: []
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return <ImageUpload fileList={this.formData.fileUrl} limit={1} isEdit={this.formDialogType !== 2} />
          }
        },
        {
          md: 24,
          isShow: true,
          name: 'el-input',
          attributes: { placeholder: '请输入备注内容', type: 'textarea', rows: 5 },
          formItemAttributes: {
            label: '备注',
            prop: 'remark',
            rules: []
          }
        }
      ]
    }
  },
  created() {
    if (this.$route.query.id) {
      this.openForm('detail', this.$route.query.id)
    }
  },
  methods: {
    // 列表请求函数
    getList: listPageV2,
    // 列表导出函数
    exportList: pageExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      if (item.jname === 'fileUrl') {
        defaultData.render = (h, { row, index, column }) => {
          return (
            <div style="padding:0 6px;cursor: pointer;">
              {row.fileUrl
                ? row.fileUrl
                    .split(',')
                    .map(url => (
                      <el-image
                        src={this.$showImgUrl(url)}
                        preview-src-list={[this.$showImgUrl(url)]}
                        fit="fit"
                        style="width:80px;height:80px;"
                      />
                    ))
                : null}
            </div>
          )
        }
      }
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },

    operation() {
      return this.operationBtn({
        detail: {
          click: ({ row, index, column }) => {
            this.openForm('detail', row.id)
          }
        }
      })
    },

    openDetail(id) {
      getDetail({ id }).then(res => {
        Object.assign(this.formData, res.data, {
          fileUrl: res.data?.fileUrl ? res.data?.fileUrl?.split(',').map(item => ({ url: item })) : [],
          worker: { workerId: res.data.workerId, nickName: res.data.workerName },
          websit: { websitId: res.data.websitId, websitName: res.data.websitName },
          examineProject: { name: res.data.examineProjectName }
        })
        this.getExamine()
        this.getWebsit()
        this.getWorker()
      })
    },
    getExamine() {
      getExamine({ pageNum: 1, pageSize: -1, params: [] }).then(res => {
        this.examineList = res.data.records
      })
    },
    getWebsit() {
      if (this.type == 0) {
        // this.formData.websitId = JSON.parse(localStorage.getItem('greemall_user')).adminWebsitId
        // this.formData.websitName = JSON.parse(localStorage.getItem('greemall_user')).nickName
      } else {
        getWebsit({ type: 'C' }).then(res => {
          this.websitList = res.data
        })
      }
    },
    getWorker() {
      getWorker({
        pageNum: 1,
        pageSize: -1,
        params: [{ param: 'b.websit_id', compare: '=', value: this.formData.websitId }]
      }).then(res => {
        this.workerList = res.data.records
      })
    },
    openForm(type, id) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: { edit: '编辑', add: '新增', detail: '详情' }[type],
        // 打开时事件
        triggerEvent: () => {
          this.formCancel()
          this.$nextTick(() => {
            this.formType = type
            this.formVisible = true
            if (type == 'add') {
              this.getExamine()
              this.getWebsit()
              this.formDialogType = 0
            } else {
              this.formDialogType = 2
              this.openDetail(id)
            }
          })
        },
        // 关闭时事件
        closeEvent: () => {}
      })
    },
    formCancel() {
      this.formVisible = false
      this.$refs?.formRef?.resetFields()
      this.$data.formData = this.$options.data().formData
    },
    formConfirm(cancel) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          ;[add, edit]
            [this.formDialogType]({
              ...this.formData,
              fileUrl: this.formData.fileUrl.map(item => item.url).join(',')
            })
            .then(res => {
              this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
              cancel('list')
              this.$refs.pageRef.refreshList()
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tab {
  padding: 20px 20px 0 20px;
}
</style>
