<template>
  <div>
    <!-- search -->
    <div style="width: 100%" v-if="lists && lists.list && lists.list.length > 0">
      <a-table
        :columns="columns"
        :data-source="lists.list"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
        bordered
        class="white pa-3"
      >
        <template slot="id" slot-scope="text, record, index">
          <span>{{ index + 1 }}</span>
        </template>

        <template slot="inputStatus" slot-scope="text, record">
          <span>
            {{
              record.inputStatus === 0
                ? '新建'
                : record.inputStatus === 1
                ? '数据收集中'
                : record.inputStatus === 2
                ? '数据收集按时完成'
                : record.inputStatus === 4
                ? '废弃'
                : record.inputStatus === 5
                ? '审核通过'
                : '已结算'
            }}
          </span>
        </template>

        <template slot="edit" slot-scope="text, record">
          <div class="d-flex flex-column">
            <a-popconfirm placement="left" ok-text="确定" cancel-text="取消" @confirm="handleOk">
              <a-icon slot="icon" type="question-circle" />
              <template slot="title">
                <div style="width: auto">
                  您是否要为<br />住院号为：{{ hospitalization }} , 研究编号为: {{ recordCode }}<br />的病例进行信息录入？
                </div>
              </template>
              <a-button
                v-if="record.inputStatus < 5"
                @click="showModal(record.id, record.hospitalization, record.code)"
                size="small"
                type="primary"
                class="mb-4"
              >
                选择
              </a-button>
            </a-popconfirm>
            <!-- <a-button @click="showModal(record.id, record.hospitalization, record.code)" class="mr-4" size="small" type="primary">
            选择
          </a-button> -->
            <a-button type="primary" size="small" @click="details(record.id, record.hospitalization, record.code)"> 查看详情 </a-button>
            <a-popconfirm placement="left" ok-text="确定" cancel-text="取消" @confirm="submit(record.id)">
              <!-- <a-icon slot="icon" type="none" /> -->
              <a-icon slot="icon" type="exclamation-circle" />
              <template slot="title">
                <div>修改状态:</div>
                <a-radio-group v-model="recordStatus">
                  <a-radio :style="radioStyle" v-for="a in status" :value="a.id" :key="a.id"> {{ a.name }} </a-radio>
                </a-radio-group>
              </template>
              <a-button class="mt-4" v-if="record.inputStatus < 5" size="small" type="primary" @click="handleChange(record.inputStatus)">
                修改状态
              </a-button>
            </a-popconfirm>
            <a-button class="mt-4" size="small" type="primary" @click="changeInfo(record.id)"> 修改基本信息 </a-button>
          </div>
        </template>

        <template slot="expandedRowRender" slot-scope="record">
          <div class="d-flex flex-wrap">
            <p class="fill-width">住院号： {{ record.hospitalization }}</p>
            <p class="fill-width">主治医生： {{ record.doctorName }}</p>
            <p class="fill-width">
              状态：
              {{
                record.inputStatus === 0
                  ? '新建'
                  : record.inputStatus === 1
                  ? '数据收集中'
                  : record.inputStatus === 2
                  ? '数据收集按时完成'
                  : record.inputStatus === 4
                  ? '废弃'
                  : record.inputStatus === 5
                  ? '审核通过'
                  : '已结算'
              }}.
            </p>
          </div>
        </template>
      </a-table>
    </div>
    <a-empty v-else />
    <a-modal title="修改基本信息" width="600px" v-model="visible" :mask-closable="false" :closable="false" :footer="null">
      <a-form :form="form" @submit="handleSubmit" ref="form" v-if="patientObj">
        <!-- 研究编号 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="研究序号">
          <a-input-number
            style="width: 100%"
            placeholder="研究序号"
            :min="0"
            :max="999"
            v-decorator="[
              'codeNum',
              {
                initialValue: patientObj.codeNum,
                rules: [{ required: true, message: '研究序号不能为空' }],
              },
            ]"
          />
        </a-form-item>
        <!-- 住院号 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="住院号">
          <a-input
            style="width: 100%"
            placeholder="住院号"
            v-decorator="[
              'hospitalization',
              {
                initialValue: patientObj.hospitalization,
                rules: [{ required: true, message: '住院号不能为空' }],
              },
            ]"
          />
        </a-form-item>
        <!-- 组别 -->
        <a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="组别">
          <a-select
            placeholder="请选择组别"
            v-decorator="[
              'inpatientId',
              {
                initialValue: patientObj.inpatientId,
                rules: [{ required: true, message: '组别不能为空' }],
              },
            ]"
          >
            <a-select-option :key="index" :value="group.id" v-for="(group, index) in controlList">{{ group.name }}</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item class="d-flex flex-row-reverse">
          <a-button @click="visible = false" class="mr-3">取消</a-button>
          <a-button class="white--text" html-type="submit" type="primary">修改</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { mapMutations, mapState } from 'vuex';
import { checkPatientComplete, upPatientMes, getById, upPatient, queryEnable } from 'config/api';

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const tailItemLayout = { wrapperCol: { span: 16, offset: 6 } };
export default {
  name: 'PatientTable',

  props: { lists: { type: Object, default: null } },

  data() {
    return {
      formItemLayout,
      tailItemLayout,
      form: this.$form.createForm(this, { name: 'r-d-add' }),
      columns: [],
      loading: false,
      hasPatientId: false,
      patientId: '', // 病例Id
      hospitalization: '', // 病例住院号
      recordCode: '', // 病例研究编号
      status: [
        { name: '新建', id: 0 },
        { name: '数据搜集中', id: 1 },
        { name: '数据搜集完成', id: 2 },
        { name: '废弃', id: 4 },
      ],
      statusModal: false,
      recordStatus: 0,
      recordId: '',
      radioStyle: {
        width: '200px',
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      isMobile: false,
      visible: false,
      patientObj: null,
      controlList: [],
      updataId: '',
    };
  },

  computed: {
    pagination() {
      const { pageNum, pageSize, total } = this.lists;
      return {
        current: pageNum,
        pageSize,
        total: +total,
      };
    },
  },

  mounted() {
    if (this._isMobile()) {
      this.columns = [
        {
          title: '研究编号',
          align: 'center',
          dataIndex: 'code',
          width: 100,
          key: 'code',
        },
        {
          title: '组别',
          align: 'center',
          dataIndex: 'name',
          width: 160,
          key: 'name',
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'edit',
          key: 'edit',
          width: 80,
          textAlign: 'center',
          scopedSlots: { customRender: 'edit' },
        },
      ];
    } else {
      this.columns = [
        {
          title: '研究编号',
          align: 'center',
          dataIndex: 'code',
          width: 100,
          key: 'code',
        },
        {
          title: '住院号',
          align: 'center',
          dataIndex: 'hospitalization',
          width: 160,
          key: 'hospitalization',
        },
        {
          title: '主治医生',
          align: 'center',
          dataIndex: 'doctorName',
          width: 100,
          key: 'doctorName',
        },
        {
          title: '组别',
          align: 'center',
          dataIndex: 'name',
          width: 160,
          key: 'name',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'inputStatus',
          key: 'inputStatus',
          width: 120,
          scopedSlots: { customRender: 'inputStatus' },
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'edit',
          key: 'edit',
          width: 80,
          textAlign: 'center',
          scopedSlots: { customRender: 'edit' },
        },
      ];
    }
  },

  created() {
    this.getList();
  },

  methods: {
    ...mapMutations('home', ['setPatientId', 'setHospitalization', 'setRecordCode', 'setShowTable']),
    async getList() {
      try {
        const res = await queryEnable({});
        const { code, msg, data } = res.data;
        if (code === 200) {
          this.controlList = data;
        } else {
          console.log(msg);
        }
      } catch (error) {
        console.error(error);
      }
    },
    // 修改基本信息
    async changeInfo(patientId) {
      try {
        this.visible = true;
        this.updataId = patientId;
        const params = { param: { patientId } };
        const res = await getById(params);
        const { code, msg, data } = res.data;
        if (code === 200) {
          this.patientObj = data;
        } else {
          console.log(msg);
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 提交表单
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFieldsAndScroll(async (err, values) => {
        if (!err) {
          try {
            const params = { param: { ...values, id: this.updataId } };
            const res = await upPatient(params);
            const { data, msg, code } = res.data;
            if (code === 200) {
              this.$message.success('修改成功');
              this.visible = false;
              this.$emit('searchPatientMes');
              // 清空表单
              this.form.resetFields();
            } else {
              throw msg;
            }
          } catch (error) {
            // console.log('error: ', error);
            this.$message.error(error || '修改失败');
          }
        }
      });
    },
    showModal(id, hospitalization, recordCode) {
      this.patientId = id;
      this.hospitalization = hospitalization;
      this.recordCode = recordCode;
    },
    _isMobile() {
      let flag = navigator.userAgent.match(
        /phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone/i,
      );
      return flag;
    },

    handleOk() {
      this.chooseItem(this.patientId, this.hospitalization, this.recordCode);
    },
    handleChange(e) {
      this.recordStatus = e;
    },
    // 修改审核状态
    async submit(id) {
      try {
        const params = {
          param: {
            id,
            inputStatus: typeof this.recordStatus === 'number' ? this.recordStatus : this.recordStatus.target.value,
          },
        };
        const res = await upPatientMes(params);
        const { code, msg, data } = res.data;
        if (code === 200) {
          this.$emit('handleSelPatientMes');
          this.statusModal = false;
          this.$message.success('修改成功');
        } else {
          this.$message.error('修改失败');
        }
      } catch (error) {
        this.$message.error(error);
      }
    },
    // 选择病患
    chooseItem(id, hospitalization, recordCode) {
      this.setPatientId(id);
      this.setHospitalization(hospitalization);
      this.setRecordCode(recordCode);
      localStorage.setItem('patientId', id);
      localStorage.setItem('hospitalization', hospitalization);
      localStorage.setItem('recordCode', recordCode);
      this.generator(id, hospitalization);
    },
    // 生成新报告单
    async generator(patientId, serialNumber) {
      try {
        const params = {
          param: {
            patientId,
            serialNumber,
          },
        };
        const res = await checkPatientComplete(params);
        const { code, msg, data } = res.data;
        // console.log(data);
        if (code === 200) {
          // console.log(data);
          localStorage.setItem('reportId', data.id);
        }
        if (localStorage.getItem('patientId') && localStorage.getItem('hospitalization')) {
          this.$message.success('选择成功');
          this.setShowTable(1);
        }
      } catch (error) {
        // console.log(error);
      }
    },
    // 页码跳转
    handleTableChange(pagination) {
      const { current } = pagination;
      this.$emit('handleSelPatientMes', current);
    },

    // 查看病例的详情
    details(Id, hospitalization, code) {
      this.setPatientId(Id);
      this.setHospitalization(hospitalization);
      this.setRecordCode(code);
      localStorage.setItem('patientId', Id);
      localStorage.setItem('hospitalization', hospitalization);
      localStorage.setItem('recordCode', code);
      const path = this.$route.path;
      this.$router.push({
        path: '/patientInfo',
        query: { path },
      });
    },
  },
};
</script>
